code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A ( lowerCAmelCase , unittest.TestCase ): snake_case__ : List[Any] = ProphetNetTokenizer snake_case__ : Dict = False def A__ ( self ): """simple docstring""" super().setUp() lowercase = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] lowercase = 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 A__ ( self , __lowerCAmelCase ): """simple docstring""" lowercase = """UNwant\u00E9d,running""" lowercase = """unwanted, running""" return input_text, output_text def A__ ( self ): """simple docstring""" lowercase = self.tokenizer_class(self.vocab_file ) lowercase = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(__lowerCAmelCase , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def A__ ( self ): """simple docstring""" lowercase = BasicTokenizer(do_lower_case=__lowerCAmelCase , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def A__ ( self ): """simple docstring""" lowercase = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] lowercase = {} for i, token in enumerate(__lowerCAmelCase ): lowercase = i lowercase = WordpieceTokenizer(vocab=__lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) @require_torch def A__ ( self ): """simple docstring""" lowercase = self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" ) lowercase = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] lowercase = [1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102] lowercase = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) lowercase = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A__ ( self ): """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def A__ ( self ): """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def A__ ( self ): """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) @slow def A__ ( self ): """simple docstring""" lowercase = self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" ) lowercase = tokenizer.encode("""sequence builders""" , add_special_tokens=__lowerCAmelCase ) lowercase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__lowerCAmelCase ) lowercase = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase ) lowercase = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase , __lowerCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
197
"""simple docstring""" from ..utils import DummyObject, requires_backends class _A ( metaclass=lowerCAmelCase ): snake_case__ : Optional[int] = ['torch', 'torchsde'] def __init__( self , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def A__ ( cls , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def A__ ( cls , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" requires_backends(cls , ["""torch""", """torchsde"""] )
197
1
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def UpperCAmelCase ( a_ , a_ ) -> Optional[int]: """simple docstring""" __A = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" __A = Image.open(requests.get(a_ , stream=a_ ).raw ).convert("RGB" ) __A = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ), ] ) __A = transform(a_ ).unsqueeze(0 ).to(a_ ) return image def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if "visual_encoder" in key: __A = re.sub("visual_encoder*" , "vision_model.encoder" , a_ ) if "blocks" in key: __A = re.sub(r"blocks" , "layers" , a_ ) if "attn" in key: __A = re.sub(r"attn" , "self_attn" , a_ ) if "norm1" in key: __A = re.sub(r"norm1" , "layer_norm1" , a_ ) if "norm2" in key: __A = re.sub(r"norm2" , "layer_norm2" , a_ ) if "encoder.norm" in key: __A = re.sub(r"encoder.norm" , "post_layernorm" , a_ ) if "encoder.patch_embed.proj" in key: __A = re.sub(r"encoder.patch_embed.proj" , "embeddings.patch_embedding" , a_ ) if "encoder.pos_embed" in key: __A = re.sub(r"encoder.pos_embed" , "embeddings.position_embedding" , a_ ) if "encoder.cls_token" in key: __A = re.sub(r"encoder.cls_token" , "embeddings.class_embedding" , a_ ) if "self_attn" in key: __A = re.sub(r"self_attn.proj" , "self_attn.projection" , a_ ) return key @torch.no_grad() def UpperCAmelCase ( a_ , a_=None ) -> Dict: """simple docstring""" if config_path is not None: __A = BlipConfig.from_pretrained(a_ ) else: __A = BlipConfig(projection_dim=5_1_2 , text_config={} , vision_config={} ) __A = BlipForConditionalGeneration(a_ ).eval() __A = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" __A = blip_decoder(pretrained=a_ , image_size=3_8_4 , vit="base" ) __A = pt_model.eval() __A = pt_model.state_dict() for key in modified_state_dict.copy(): __A = modified_state_dict.pop(a_ ) __A = rename_key(a_ ) __A = value hf_model.load_state_dict(a_ ) __A = 3_8_4 __A = load_demo_image(image_size=a_ , device="cpu" ) __A = BertTokenizer.from_pretrained("bert-base-uncased" ) __A = tokenizer(["a picture of"] ).input_ids __A = hf_model.generate(a_ , a_ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 3_8_6_1, 1_9_9_7, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] __A = hf_model.generate(a_ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(a_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __A = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) __A = blip_vqa(pretrained=a_ , image_size=a_ , vit="base" ) vqa_model.eval() __A = vqa_model.state_dict() for key in modified_state_dict.copy(): __A = modified_state_dict.pop(a_ ) __A = rename_key(a_ ) __A = value __A = BlipForQuestionAnswering(a_ ) hf_vqa_model.load_state_dict(a_ ) __A = ["How many dogs are in this image?"] __A = tokenizer(a_ , return_tensors="pt" ).input_ids __A = hf_vqa_model.generate(a_ , a_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) __A = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" __A = blip_itm(pretrained=a_ , image_size=a_ , vit="base" ) itm_model.eval() __A = itm_model.state_dict() for key in modified_state_dict.copy(): __A = modified_state_dict.pop(a_ ) __A = rename_key(a_ ) __A = value __A = BlipForImageTextRetrieval(a_ ) __A = ["A picture of a woman with a dog sitting in a beach"] __A = tokenizer( a_ , return_tensors="pt" , padding="max_length" , truncation=a_ , max_length=3_5 , ).input_ids hf_itm_model.load_state_dict(a_ ) hf_itm_model.eval() __A = hf_itm_model(a_ , a_ , use_itm_head=a_ ) __A = hf_itm_model(a_ , a_ , use_itm_head=a_ ) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[str] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :str = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
124
import argparse from collections import defaultdict import yaml SCREAMING_SNAKE_CASE :str = 'docs/source/en/_toctree.yml' def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = defaultdict(a_ ) for doc in model_doc: counts[doc["local"]] += 1 __A = [key for key, value in counts.items() if value > 1] __A = [] for duplicate_key in duplicates: __A = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key} ) if len(a_ ) > 1: raise ValueError( F'''{duplicate_key} is present several times in the documentation table of content at ''' "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " "others." ) # Only add this once new_doc.append({"local": duplicate_key, "title": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1] ) # Sort return sorted(a_ , key=lambda a_ : s["title"].lower() ) def UpperCAmelCase ( a_=False ) -> List[Any]: """simple docstring""" with open(a_ , encoding="utf-8" ) as f: __A = yaml.safe_load(f.read() ) # Get to the API doc __A = 0 while content[api_idx]["title"] != "API": api_idx += 1 __A = content[api_idx]["sections"] # Then to the model doc __A = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 __A = api_doc[model_idx]["sections"] __A = [(idx, section) for idx, section in enumerate(a_ ) if "sections" in section] __A = False for idx, modality_doc in modalities_docs: __A = modality_doc["sections"] __A = clean_model_doc_toc(a_ ) if old_modality_doc != new_modality_doc: __A = True if overwrite: __A = new_modality_doc if diff: if overwrite: __A = model_doc __A = api_doc with open(a_ , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(a_ , allow_unicode=a_ ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') SCREAMING_SNAKE_CASE :List[str] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
124
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class A_ : """simple docstring""" def __init__( self :List[str] , lowercase_ :str , lowercase_ :Dict=12 , lowercase_ :Dict=7 , lowercase_ :str=True , lowercase_ :List[Any]=True , lowercase_ :Dict=True , lowercase_ :Optional[int]=99 , lowercase_ :Dict=32 , lowercase_ :Optional[Any]=32 , lowercase_ :Union[str, Any]=2 , lowercase_ :List[str]=4 , lowercase_ :Optional[int]=37 , lowercase_ :Union[str, Any]=0.1 , lowercase_ :Optional[int]=0.1 , lowercase_ :int=5_12 , lowercase_ :List[Any]=0.02 , lowercase_ :Any=0 , lowercase_ :List[Any]=None , ) -> int: UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = projection_dim UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = max_position_embeddings UpperCAmelCase = initializer_range UpperCAmelCase = scope UpperCAmelCase = bos_token_id def UpperCAmelCase__ ( self :List[Any] ) -> List[str]: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCAmelCase = input_mask.numpy() UpperCAmelCase , UpperCAmelCase = input_mask.shape UpperCAmelCase = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__snake_case ): UpperCAmelCase = 1 UpperCAmelCase = 0 UpperCAmelCase = self.get_config() return config, input_ids, tf.convert_to_tensor(__snake_case ) def UpperCAmelCase__ ( self :List[str] ) -> Optional[int]: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def UpperCAmelCase__ ( self :int , lowercase_ :Any , lowercase_ :List[str] , lowercase_ :List[Any] ) -> Optional[int]: UpperCAmelCase = TFBlipTextModel(config=__snake_case ) UpperCAmelCase = model(__snake_case , attention_mask=__snake_case , training=__snake_case ) UpperCAmelCase = model(__snake_case , training=__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase__ ( self :Optional[int] ) -> Any: UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A_ ( snake_case_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = (TFBlipTextModel,) if is_tf_available() else () __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def UpperCAmelCase__ ( self :List[Any] ) -> Optional[int]: UpperCAmelCase = BlipTextModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self :int ) -> List[str]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def UpperCAmelCase__ ( self :str ) -> Union[str, Any]: pass def UpperCAmelCase__ ( self :Optional[Any] ) -> Tuple: pass @unittest.skip(reason='Blip does not use inputs_embeds' ) def UpperCAmelCase__ ( self :List[Any] ) -> List[Any]: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def UpperCAmelCase__ ( self :List[Any] ) -> List[str]: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def UpperCAmelCase__ ( self :List[str] ) -> int: pass @slow def UpperCAmelCase__ ( self :List[str] ) -> List[str]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = TFBlipTextModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def UpperCAmelCase__ ( self :List[str] , lowercase_ :List[str]=True ) -> Any: super().test_pt_tf_model_equivalence(allow_missing_keys=__snake_case )
78
'''simple docstring''' import argparse import json from tqdm import tqdm def UpperCamelCase__ ( ): """simple docstring""" _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--src_path""" , type=lowerCAmelCase , default="""biencoder-nq-dev.json""" , help="""Path to raw DPR training data""" , ) parser.add_argument( """--evaluation_set""" , type=lowerCAmelCase , help="""where to store parsed evaluation_set file""" , ) parser.add_argument( """--gold_data_path""" , type=lowerCAmelCase , help="""where to store parsed gold_data_path file""" , ) _lowerCAmelCase = parser.parse_args() with open(args.src_path , """r""" ) as src_file, open(args.evaluation_set , """w""" ) as eval_file, open( args.gold_data_path , """w""" ) as gold_file: _lowerCAmelCase = json.load(lowerCAmelCase ) for dpr_record in tqdm(lowerCAmelCase ): _lowerCAmelCase = dpr_record["""question"""] _lowerCAmelCase = [context["""title"""] for context in dpr_record["""positive_ctxs"""]] eval_file.write(question + """\n""" ) gold_file.write("""\t""".join(lowerCAmelCase ) + """\n""" ) if __name__ == "__main__": main()
70
0
'''simple docstring''' import math import tensorflow as tf from packaging import version def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Dict: lowerCamelCase__ : Union[str, Any] = tf.convert_to_tensor(UpperCamelCase ) lowerCamelCase__ : List[str] = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: lowerCamelCase__ : Tuple = tf.convert_to_tensor(UpperCamelCase ) lowerCamelCase__ : int = tf.cast(math.pi , x.dtype ) lowerCamelCase__ : Optional[Any] = tf.cast(0.04_4715 , x.dtype ) lowerCamelCase__ : str = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(UpperCamelCase , 3 )) )) return x * cdf def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ : str = tf.convert_to_tensor(UpperCamelCase ) return x * tf.tanh(tf.math.softplus(UpperCamelCase ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[int]: lowerCamelCase__ : Optional[int] = tf.convert_to_tensor(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = tf.cast(0.04_4715 , x.dtype ) lowerCamelCase__ : Dict = tf.cast(0.79_7884_5608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Tuple: lowerCamelCase__ : Optional[Any] = tf.convert_to_tensor(UpperCamelCase ) lowerCamelCase__ : Any = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Any: return tf.clip_by_value(_gelu(UpperCamelCase ) , -10 , 10 ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=-1 ) -> Optional[int]: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = tf.split(UpperCamelCase , 2 , axis=UpperCamelCase ) return a * tf.math.sigmoid(UpperCamelCase ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: return tf.keras.activations.gelu(UpperCamelCase , approximate=UpperCamelCase ) _A : Any =tf.keras.activations.gelu _A : str =approximate_gelu_wrap else: _A : List[str] =_gelu _A : Union[str, Any] =_gelu_new _A : int ={ '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Dict: if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
129
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _A : Union[str, Any] =8 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=BITS ) -> Tuple: lowerCamelCase__ : List[str] = x.device lowerCamelCase__ : Any = (x * 255).int().clamp(0 , 255 ) lowerCamelCase__ : Optional[int] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCamelCase ) lowerCamelCase__ : int = rearrange(UpperCamelCase , """d -> d 1 1""" ) lowerCamelCase__ : List[str] = rearrange(UpperCamelCase , """b c h w -> b c 1 h w""" ) lowerCamelCase__ : Tuple = ((x & mask) != 0).float() lowerCamelCase__ : List[Any] = rearrange(UpperCamelCase , """b c d h w -> b (c d) h w""" ) lowerCamelCase__ : Optional[int] = bits * 2 - 1 return bits def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=BITS ) -> List[Any]: lowerCamelCase__ : List[Any] = x.device lowerCamelCase__ : Dict = (x > 0).int() lowerCamelCase__ : Optional[Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCamelCase , dtype=torch.intaa ) lowerCamelCase__ : List[Any] = rearrange(UpperCamelCase , """d -> d 1 1""" ) lowerCamelCase__ : List[str] = rearrange(UpperCamelCase , """b (c d) h w -> b c d h w""" , d=8 ) lowerCamelCase__ : List[Any] = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 255).clamp(0.0 , 1.0 ) def SCREAMING_SNAKE_CASE_ (self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 0.0 , UpperCamelCase = True , UpperCamelCase=None , UpperCamelCase = True , ) -> Union[DDIMSchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) lowerCamelCase__ : Optional[int] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas lowerCamelCase__ : str = self.alphas_cumprod[timestep] lowerCamelCase__ : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod lowerCamelCase__ : Optional[int] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf lowerCamelCase__ : Optional[int] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" lowerCamelCase__ : Dict = self.bit_scale if self.config.clip_sample: lowerCamelCase__ : Optional[Any] = torch.clamp(UpperCamelCase , -scale , UpperCamelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) lowerCamelCase__ : Tuple = self._get_variance(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Optional[int] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide lowerCamelCase__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf lowerCamelCase__ : Optional[Any] = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf lowerCamelCase__ : Tuple = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 lowerCamelCase__ : Dict = model_output.device if torch.is_tensor(UpperCamelCase ) else """cpu""" lowerCamelCase__ : str = torch.randn(model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase ).to(UpperCamelCase ) lowerCamelCase__ : Optional[Any] = self._get_variance(UpperCamelCase , UpperCamelCase ) ** 0.5 * eta * noise lowerCamelCase__ : int = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=UpperCamelCase , pred_original_sample=UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase="epsilon" , UpperCamelCase=None , UpperCamelCase = True , ) -> Union[DDPMSchedulerOutput, Tuple]: lowerCamelCase__ : List[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = torch.split(UpperCamelCase , sample.shape[1] , dim=1 ) else: lowerCamelCase__ : List[str] = None # 1. compute alphas, betas lowerCamelCase__ : str = self.alphas_cumprod[t] lowerCamelCase__ : List[str] = self.alphas_cumprod[t - 1] if t > 0 else self.one lowerCamelCase__ : str = 1 - alpha_prod_t lowerCamelCase__ : List[Any] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": lowerCamelCase__ : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": lowerCamelCase__ : Optional[Any] = model_output else: raise ValueError(f'''Unsupported prediction_type {prediction_type}.''' ) # 3. Clip "predicted x_0" lowerCamelCase__ : str = self.bit_scale if self.config.clip_sample: lowerCamelCase__ : List[Any] = torch.clamp(UpperCamelCase , -scale , UpperCamelCase ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCamelCase__ : Tuple = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t lowerCamelCase__ : Tuple = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCamelCase__ : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise lowerCamelCase__ : Optional[Any] = 0 if t > 0: lowerCamelCase__ : Optional[Any] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=UpperCamelCase ).to(model_output.device ) lowerCamelCase__ : str = (self._get_variance(UpperCamelCase , predicted_variance=UpperCamelCase ) ** 0.5) * noise lowerCamelCase__ : Optional[int] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=UpperCamelCase , pred_original_sample=UpperCamelCase ) class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: UNetaDConditionModel , UpperCamelCase__: Union[DDIMScheduler, DDPMScheduler] , UpperCamelCase__: Optional[float] = 1.0 , ): super().__init__() lowerCamelCase__ : Optional[int] = bit_scale lowerCamelCase__ : List[Any] = ( ddim_bit_scheduler_step if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) @torch.no_grad() def __call__( self: Union[str, Any] , UpperCamelCase__: Optional[int] = 256 , UpperCamelCase__: Optional[int] = 256 , UpperCamelCase__: Optional[int] = 50 , UpperCamelCase__: Optional[torch.Generator] = None , UpperCamelCase__: Optional[int] = 1 , UpperCamelCase__: Optional[str] = "pil" , UpperCamelCase__: bool = True , **UpperCamelCase__: int , ): lowerCamelCase__ : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=UpperCamelCase__ , ) lowerCamelCase__ : Union[str, Any] = decimal_to_bits(UpperCamelCase__ ) * self.bit_scale lowerCamelCase__ : Union[str, Any] = latents.to(self.device ) self.scheduler.set_timesteps(UpperCamelCase__ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual lowerCamelCase__ : Tuple = self.unet(UpperCamelCase__ , UpperCamelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase__ : Any = self.scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample lowerCamelCase__ : Dict = bits_to_decimal(UpperCamelCase__ ) if output_type == "pil": lowerCamelCase__ : int = self.numpy_to_pil(UpperCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase__ )
129
1
from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min_version, require_tpu, require_xpu, skip, slow, ) from .training import RegressionDataset, RegressionModel, RegressionModelaXPU from .scripts import test_script, test_sync, test_ops # isort: skip
76
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = seq_length _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = use_labels _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = eos_token_id _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _SCREAMING_SNAKE_CASE = tf.concat([input_ids, eos_tensor] , axis=1 ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _SCREAMING_SNAKE_CASE = prepare_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(config=A ).get_decoder() _SCREAMING_SNAKE_CASE = inputs_dict["""input_ids"""] _SCREAMING_SNAKE_CASE = input_ids[:1, :] _SCREAMING_SNAKE_CASE = inputs_dict["""attention_mask"""][:1, :] _SCREAMING_SNAKE_CASE = inputs_dict["""head_mask"""] _SCREAMING_SNAKE_CASE = 1 # first forward pass _SCREAMING_SNAKE_CASE = model(A , attention_mask=A , head_mask=A , use_cache=A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _SCREAMING_SNAKE_CASE = tf.concat([input_ids, next_tokens] , axis=-1 ) _SCREAMING_SNAKE_CASE = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _SCREAMING_SNAKE_CASE = model(A , attention_mask=A )[0] _SCREAMING_SNAKE_CASE = model(A , attention_mask=A , past_key_values=A )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _SCREAMING_SNAKE_CASE = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx] _SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A , A , rtol=1e-3 ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _SCREAMING_SNAKE_CASE = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , return_tensors="""tf""" ) _SCREAMING_SNAKE_CASE = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A , ) _SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
0
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class UpperCamelCase__ : """simple docstring""" @staticmethod def a ( *snake_case__ , **snake_case__ ): '''simple docstring''' pass def lowercase (_A ): """simple docstring""" _lowerCAmelCase : Tuple = hashlib.mda(image.tobytes() ) return m.hexdigest()[:1_0] def lowercase (_A ): """simple docstring""" _lowerCAmelCase : Union[str, Any] = np.array(snake_case__ ) _lowerCAmelCase : Dict = npimg.shape return {"hash": hashimage(snake_case__ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" __magic_name__ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) __magic_name__ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def a ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Dict = MaskGenerationPipeline(model=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def a ( self , snake_case__ , snake_case__ ): '''simple docstring''' pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def a ( self ): '''simple docstring''' pass @slow @require_torch def a ( self ): '''simple docstring''' _lowerCAmelCase : Any = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) _lowerCAmelCase : List[Any] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing _lowerCAmelCase : Tuple = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9967}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9909}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9879}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9834}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9716}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9612}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9599}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9552}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9532}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9516}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9499}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9483}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9464}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9408}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9335}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9326}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9262}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8999}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8986}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8984}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8873}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8871} ] , ) # fmt: on @require_torch @slow def a ( self ): '''simple docstring''' _lowerCAmelCase : Dict = 'facebook/sam-vit-huge' _lowerCAmelCase : List[Any] = pipeline('mask-generation' , model=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase : List[str] = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing _lowerCAmelCase : Dict = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0210}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053}, ] , )
364
'''simple docstring''' def lowercase (_A = 1_0_0_0_0_0_0 ): """simple docstring""" _lowerCAmelCase : Any = set(range(3 , _A , 2 ) ) primes.add(2 ) for p in range(3 , _A , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , _A , _A ) ) ) _lowerCAmelCase : Union[str, Any] = [float(_A ) for n in range(limit + 1 )] for p in primes: for n in range(_A , limit + 1 , _A ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'''{solution() = }''')
25
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING a__ : List[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = { "Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json", } class UpperCamelCase__ ( SCREAMING_SNAKE_CASE): UpperCAmelCase__ : List[str] = 'instructblip_vision_model' def __init__( self :List[str] , _A :str=1_408 , _A :List[str]=6_144 , _A :List[Any]=39 , _A :Optional[Any]=16 , _A :Tuple=224 , _A :Tuple=14 , _A :Tuple="gelu" , _A :Optional[Any]=1E-6 , _A :List[Any]=0.0 , _A :Dict=1E-10 , _A :List[str]=True , **_A :Dict , ) -> Dict: '''simple docstring''' super().__init__(**_A ) __A = hidden_size __A = intermediate_size __A = num_hidden_layers __A = num_attention_heads __A = patch_size __A = image_size __A = initializer_range __A = attention_dropout __A = layer_norm_eps __A = hidden_act __A = qkv_bias @classmethod def lowercase_ ( cls :Any , _A :Union[str, os.PathLike] , **_A :Tuple ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_A ) __A , __A = cls.get_config_dict(_A , **_A ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __A = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_A , **_A ) class UpperCamelCase__ ( SCREAMING_SNAKE_CASE): UpperCAmelCase__ : List[str] = 'instructblip_qformer' def __init__( self :Tuple , _A :int=30_522 , _A :List[str]=768 , _A :str=12 , _A :Optional[Any]=12 , _A :Union[str, Any]=3_072 , _A :str="gelu" , _A :Tuple=0.1 , _A :Dict=0.1 , _A :Dict=512 , _A :Union[str, Any]=0.02 , _A :int=1E-12 , _A :str=0 , _A :Union[str, Any]="absolute" , _A :List[str]=2 , _A :Optional[Any]=1_408 , **_A :Any , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=_A , **_A ) __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = hidden_act __A = intermediate_size __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = initializer_range __A = layer_norm_eps __A = position_embedding_type __A = cross_attention_frequency __A = encoder_hidden_size @classmethod def lowercase_ ( cls :int , _A :Union[str, os.PathLike] , **_A :int ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_A ) __A , __A = cls.get_config_dict(_A , **_A ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __A = config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_A , **_A ) class UpperCamelCase__ ( SCREAMING_SNAKE_CASE): UpperCAmelCase__ : Any = 'instructblip' UpperCAmelCase__ : List[Any] = True def __init__( self :Dict , _A :int=None , _A :Optional[Any]=None , _A :Optional[Any]=None , _A :Optional[Any]=32 , **_A :List[Any] ) -> Tuple: '''simple docstring''' super().__init__(**_A ) if vision_config is None: __A = {} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __A = {} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __A = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __A = InstructBlipVisionConfig(**_A ) __A = InstructBlipQFormerConfig(**_A ) __A = text_config['model_type'] if 'model_type' in text_config else 'opt' __A = CONFIG_MAPPING[text_model_type](**_A ) __A = self.text_config.tie_word_embeddings __A = self.text_config.is_encoder_decoder __A = num_query_tokens __A = self.vision_config.hidden_size __A = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __A = 1.0 __A = 0.02 @classmethod def lowercase_ ( cls :int , _A :InstructBlipVisionConfig , _A :InstructBlipQFormerConfig , _A :PretrainedConfig , **_A :Any , ) -> Any: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_A , ) def lowercase_ ( self :int ) -> Tuple: '''simple docstring''' __A = copy.deepcopy(self.__dict__ ) __A = self.vision_config.to_dict() __A = self.qformer_config.to_dict() __A = self.text_config.to_dict() __A = self.__class__.model_type return output
161
'''simple docstring''' import functools def snake_case ( UpperCAmelCase , UpperCAmelCase )-> int: """simple docstring""" # Validation if not isinstance(UpperCAmelCase , UpperCAmelCase ) or not all(isinstance(UpperCAmelCase , UpperCAmelCase ) for day in days ): raise ValueError('The parameter days should be a list of integers' ) if len(UpperCAmelCase ) != 3 or not all(isinstance(UpperCAmelCase , UpperCAmelCase ) for cost in costs ): raise ValueError('The parameter costs should be a list of three integers' ) if len(UpperCAmelCase ) == 0: return 0 if min(UpperCAmelCase ) <= 0: raise ValueError('All days elements should be greater than 0' ) if max(UpperCAmelCase ) >= 3_6_6: raise ValueError('All days elements should be less than 366' ) __A = set(UpperCAmelCase ) @functools.cache def dynamic_programming(UpperCAmelCase ) -> int: if index > 3_6_5: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 3_0 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
161
1
import math import sys def A_ ( _UpperCAmelCase ): if number != int(_UpperCAmelCase ): raise ValueError("the value of input must be a natural number" ) if number < 0: raise ValueError("the value of input must not be a negative number" ) if number == 0: return 1 SCREAMING_SNAKE_CASE_: Dict = [-1] * (number + 1) SCREAMING_SNAKE_CASE_: Dict = 0 for i in range(1 , number + 1 ): SCREAMING_SNAKE_CASE_: int = sys.maxsize SCREAMING_SNAKE_CASE_: Any = int(math.sqrt(_UpperCAmelCase ) ) for j in range(1 , root + 1 ): SCREAMING_SNAKE_CASE_: Any = 1 + answers[i - (j**2)] SCREAMING_SNAKE_CASE_: List[str] = min(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
127
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : int): SCREAMING_SNAKE_CASE_: str = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") SCREAMING_SNAKE_CASE_: str = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = -1 SCREAMING_SNAKE_CASE_: Optional[int] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = model.generate(lowerCAmelCase__ , max_new_tokens=10 , do_sample=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = tokenizer.decode(greedy_ids[0]) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_: int = TextStreamer(lowerCAmelCase__) model.generate(lowerCAmelCase__ , max_new_tokens=10 , do_sample=lowerCAmelCase__ , streamer=lowerCAmelCase__) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE_: Union[str, Any] = cs.out[:-1] self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : int): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") SCREAMING_SNAKE_CASE_: int = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = -1 SCREAMING_SNAKE_CASE_: int = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = model.generate(lowerCAmelCase__ , max_new_tokens=10 , do_sample=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = tokenizer.decode(greedy_ids[0]) SCREAMING_SNAKE_CASE_: int = TextIteratorStreamer(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE_: Tuple = Thread(target=model.generate , kwargs=lowerCAmelCase__) thread.start() SCREAMING_SNAKE_CASE_: Optional[Any] = "" for new_text in streamer: streamer_text += new_text self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): SCREAMING_SNAKE_CASE_: int = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") SCREAMING_SNAKE_CASE_: int = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = -1 SCREAMING_SNAKE_CASE_: Optional[Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = model.generate(lowerCAmelCase__ , max_new_tokens=10 , do_sample=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = greedy_ids[:, input_ids.shape[1] :] SCREAMING_SNAKE_CASE_: Union[str, Any] = tokenizer.decode(new_greedy_ids[0]) with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_: Dict = TextStreamer(lowerCAmelCase__ , skip_prompt=lowerCAmelCase__) model.generate(lowerCAmelCase__ , max_new_tokens=10 , do_sample=lowerCAmelCase__ , streamer=lowerCAmelCase__) # The greedy text should be printed to stdout, except for the final "\n" in the streamer SCREAMING_SNAKE_CASE_: Any = cs.out[:-1] self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Tuple): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them SCREAMING_SNAKE_CASE_: Tuple = AutoTokenizer.from_pretrained("distilgpt2") SCREAMING_SNAKE_CASE_: List[str] = AutoModelForCausalLM.from_pretrained("distilgpt2").to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = -1 SCREAMING_SNAKE_CASE_: List[str] = torch.ones((1, 5) , device=lowerCAmelCase__).long() * model.config.bos_token_id with CaptureStdout() as cs: SCREAMING_SNAKE_CASE_: Union[str, Any] = TextStreamer(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__) model.generate(lowerCAmelCase__ , max_new_tokens=1 , do_sample=lowerCAmelCase__ , streamer=lowerCAmelCase__) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token SCREAMING_SNAKE_CASE_: str = cs.out[:-1] # Remove the final "\n" SCREAMING_SNAKE_CASE_: Tuple = tokenizer(lowerCAmelCase__ , return_tensors="pt") self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") SCREAMING_SNAKE_CASE_: List[str] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = -1 SCREAMING_SNAKE_CASE_: List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = TextIteratorStreamer(lowerCAmelCase__ , timeout=0.001) SCREAMING_SNAKE_CASE_: Any = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} SCREAMING_SNAKE_CASE_: Optional[Any] = Thread(target=model.generate , kwargs=lowerCAmelCase__) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(lowerCAmelCase__): SCREAMING_SNAKE_CASE_: Tuple = "" for new_text in streamer: streamer_text += new_text
127
1
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def UpperCamelCase ( lowerCAmelCase__ = 3 ): '''simple docstring''' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError('''number of qubits must be a integer.''' ) if number_of_qubits <= 0: raise ValueError('''number of qubits must be > 0.''' ) if math.floor(lowerCAmelCase__ ) != number_of_qubits: raise ValueError('''number of qubits must be exact integer.''' ) if number_of_qubits > 10: raise ValueError('''number of qubits too large to simulate(>10).''' ) lowercase = QuantumRegister(lowerCAmelCase__ , '''qr''' ) lowercase = ClassicalRegister(lowerCAmelCase__ , '''cr''' ) lowercase = QuantumCircuit(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase = number_of_qubits for i in range(lowerCAmelCase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowerCAmelCase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowerCAmelCase__ , lowerCAmelCase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowerCAmelCase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowerCAmelCase__ , lowerCAmelCase__ ) # simulate with 10000 shots lowercase = Aer.get_backend('''qasm_simulator''' ) lowercase = execute(lowerCAmelCase__ , lowerCAmelCase__ , shots=1_0000 ) return job.result().get_counts(lowerCAmelCase__ ) if __name__ == "__main__": print( F'Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}' )
101
import random from .binary_exp_mod import bin_exp_mod def A ( a_ ,a_=1_000 ) -> Optional[Any]: if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd __UpperCamelCase : List[Any] =n - 1 __UpperCamelCase : Dict =0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) __UpperCamelCase : Optional[Any] =0 while count < prec: __UpperCamelCase : Dict =random.randint(2 ,n - 1 ) __UpperCamelCase : Optional[Any] =bin_exp_mod(a_ ,a_ ,a_ ) if b != 1: __UpperCamelCase : List[str] =True for _ in range(a_ ): if b == n - 1: __UpperCamelCase : Tuple =False break __UpperCamelCase : Dict =b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": A_ :str = abs(int(input('''Enter bound : ''').strip())) print('''Here\'s the list of primes:''') print(''', '''.join(str(i) for i in range(n + 1) if is_prime_big(i)))
71
0
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger('''transformers.models.speecht5''') def lowerCamelCase (a_ :List[Any] , a_ :str , a_ :List[str]) -> Any: hf_model.apply_weight_norm() lowercase :List[str] = checkpoint['input_conv.weight_g'] lowercase :Union[str, Any] = checkpoint['input_conv.weight_v'] lowercase :Optional[Any] = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates)): lowercase :Union[str, Any] = checkpoint[F"""upsamples.{i}.1.weight_g"""] lowercase :List[str] = checkpoint[F"""upsamples.{i}.1.weight_v"""] lowercase :List[str] = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates) * len(config.resblock_kernel_sizes)): for j in range(len(config.resblock_dilation_sizes)): lowercase :Tuple = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] lowercase :Optional[Any] = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] lowercase :Optional[Any] = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] lowercase :str = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] lowercase :List[str] = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] lowercase :Tuple = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] lowercase :int = checkpoint['output_conv.1.weight_g'] lowercase :List[str] = checkpoint['output_conv.1.weight_v'] lowercase :int = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def lowerCamelCase (a_ :Union[str, Any] , a_ :Optional[Any] , a_ :Dict , a_ :Optional[Any]=None , a_ :Tuple=None , ) -> str: if config_path is not None: lowercase :Any = SpeechTaHifiGanConfig.from_pretrained(a_) else: lowercase :List[Any] = SpeechTaHifiGanConfig() lowercase :str = SpeechTaHifiGan(a_) lowercase :str = torch.load(a_) load_weights(orig_checkpoint['''model''']['''generator'''] , a_ , a_) lowercase :Optional[Any] = np.load(a_) lowercase :str = stats[0].reshape(-1) lowercase :List[Any] = stats[1].reshape(-1) lowercase :Optional[Any] = torch.from_numpy(a_).float() lowercase :Tuple = torch.from_numpy(a_).float() model.save_pretrained(a_) if repo_id: print('''Pushing to the hub...''') model.push_to_hub(a_) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--stats_path''', required=True, default=None, type=str, help='''Path to stats.npy file''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCAmelCase = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
356
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = "layoutlmv3" def __init__( self : int , snake_case__ : Any=5_0_2_6_5 , snake_case__ : int=7_6_8 , snake_case__ : Dict=1_2 , snake_case__ : Optional[Any]=1_2 , snake_case__ : Union[str, Any]=3_0_7_2 , snake_case__ : Tuple="gelu" , snake_case__ : List[str]=0.1 , snake_case__ : List[str]=0.1 , snake_case__ : int=5_1_2 , snake_case__ : int=2 , snake_case__ : Optional[int]=0.02 , snake_case__ : Union[str, Any]=1e-5 , snake_case__ : Optional[int]=1 , snake_case__ : Any=0 , snake_case__ : Optional[int]=2 , snake_case__ : int=1_0_2_4 , snake_case__ : str=1_2_8 , snake_case__ : Tuple=1_2_8 , snake_case__ : Optional[Any]=True , snake_case__ : Union[str, Any]=3_2 , snake_case__ : Any=1_2_8 , snake_case__ : List[Any]=6_4 , snake_case__ : List[Any]=2_5_6 , snake_case__ : Any=True , snake_case__ : Optional[Any]=True , snake_case__ : Tuple=True , snake_case__ : List[Any]=2_2_4 , snake_case__ : Optional[int]=3 , snake_case__ : Union[str, Any]=1_6 , snake_case__ : str=None , **snake_case__ : List[str] , ): '''simple docstring''' super().__init__( vocab_size=snake_case__ , hidden_size=snake_case__ , num_hidden_layers=snake_case__ , num_attention_heads=snake_case__ , intermediate_size=snake_case__ , hidden_act=snake_case__ , hidden_dropout_prob=snake_case__ , attention_probs_dropout_prob=snake_case__ , max_position_embeddings=snake_case__ , type_vocab_size=snake_case__ , initializer_range=snake_case__ , layer_norm_eps=snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ , ) lowercase :Optional[int] = max_ad_position_embeddings lowercase :Tuple = coordinate_size lowercase :Any = shape_size lowercase :Union[str, Any] = has_relative_attention_bias lowercase :Optional[Any] = rel_pos_bins lowercase :Tuple = max_rel_pos lowercase :Any = has_spatial_attention_bias lowercase :Any = rel_ad_pos_bins lowercase :str = max_rel_ad_pos lowercase :int = text_embed lowercase :Optional[int] = visual_embed lowercase :str = input_size lowercase :List[str] = num_channels lowercase :str = patch_size lowercase :Any = classifier_dropout class __magic_name__ ( __UpperCAmelCase ): __A : Tuple = version.parse("1.12" ) @property def __snake_case ( self : Any ): '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __snake_case ( self : int ): '''simple docstring''' return 1e-5 @property def __snake_case ( self : Union[str, Any] ): '''simple docstring''' return 1_2 def __snake_case ( self : str , snake_case__ : "ProcessorMixin" , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 3 , snake_case__ : int = 4_0 , snake_case__ : int = 4_0 , ): '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , snake_case__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase :Dict = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowercase :Union[str, Any] = processor.tokenizer.num_special_tokens_to_add(snake_case__ ) lowercase :List[str] = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case__ ) # Generate dummy inputs according to compute batch and sequence lowercase :Tuple = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes lowercase :List[str] = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) lowercase :List[Any] = self._generate_dummy_images(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowercase :Dict = dict( processor( snake_case__ , text=snake_case__ , boxes=snake_case__ , return_tensors=snake_case__ , ) ) return inputs
172
0
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class A__ : lowercase = 42 # setable values lowercase = 42 lowercase = 42 lowercase = None @classmethod def snake_case_ ( cls , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: '''simple docstring''' return cls(common=UpperCamelCase__ , init_noise_sigma=UpperCamelCase__ , timesteps=UpperCamelCase__ ) @dataclass class A__ ( _snake_case ): lowercase = 42 class A__ ( _snake_case , _snake_case ): lowercase = [e.name for e in FlaxKarrasDiffusionSchedulers] lowercase = 42 @property def snake_case_ ( self ) -> List[str]: '''simple docstring''' return True @register_to_config def __init__( self , UpperCamelCase__ = 1000 , UpperCamelCase__ = 0.0001 , UpperCamelCase__ = 0.02 , UpperCamelCase__ = "linear" , UpperCamelCase__ = None , UpperCamelCase__ = "fixed_small" , UpperCamelCase__ = True , UpperCamelCase__ = "epsilon" , UpperCamelCase__ = jnp.floataa , ) -> List[Any]: '''simple docstring''' A_ = dtype def snake_case_ ( self , UpperCamelCase__ = None ) -> DDPMSchedulerState: '''simple docstring''' if common is None: A_ = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution A_ = jnp.array(1.0 , dtype=self.dtype ) A_ = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=UpperCamelCase__ , init_noise_sigma=UpperCamelCase__ , timesteps=UpperCamelCase__ , ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None ) -> jnp.ndarray: '''simple docstring''' return sample def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = () ) -> DDPMSchedulerState: '''simple docstring''' A_ = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 A_ = (jnp.arange(0 , UpperCamelCase__ ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=UpperCamelCase__ , timesteps=UpperCamelCase__ , ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None ) -> Optional[Any]: '''simple docstring''' A_ = state.common.alphas_cumprod[t] A_ = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample A_ = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: A_ = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": A_ = jnp.clip(UpperCamelCase__ , a_min=1e-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": A_ = jnp.log(jnp.clip(UpperCamelCase__ , a_min=1e-2_0 ) ) elif variance_type == "fixed_large": A_ = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log A_ = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": A_ = variance A_ = state.common.betas[t] A_ = (predicted_variance + 1) / 2 A_ = frac * max_log + (1 - frac) * min_log return variance def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: '''simple docstring''' A_ = timestep if key is None: A_ = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: A_ , A_ = jnp.split(UpperCamelCase__ , sample.shape[1] , axis=1 ) else: A_ = None # 1. compute alphas, betas A_ = state.common.alphas_cumprod[t] A_ = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) A_ = 1 - alpha_prod_t A_ = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": A_ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": A_ = model_output elif self.config.prediction_type == "v_prediction": A_ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' """ for the FlaxDDPMScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: A_ = jnp.clip(UpperCamelCase__ , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A_ = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t A_ = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A_ = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): A_ = jax.random.split(UpperCamelCase__ , num=1 ) A_ = jax.random.normal(UpperCamelCase__ , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(UpperCamelCase__ , UpperCamelCase__ , predicted_variance=UpperCamelCase__ ) ** 0.5) * noise A_ = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) A_ = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=UpperCamelCase__ , state=UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) -> jnp.ndarray: '''simple docstring''' return add_noise_common(state.common , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) -> jnp.ndarray: '''simple docstring''' return get_velocity_common(state.common , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __len__( self ) -> Union[str, Any]: '''simple docstring''' return self.config.num_train_timesteps
162
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class A__ ( unittest.TestCase ): lowercase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowercase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' A_ = TextaTextGenerationPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) return generator, ["Something to write", "Something else"] def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Any: '''simple docstring''' A_ = generator("""Something there""" ) self.assertEqual(UpperCamelCase__ , [{"""generated_text""": ANY(UpperCamelCase__ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) A_ = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{"""generated_text""": ANY(UpperCamelCase__ )}, {"""generated_text""": ANY(UpperCamelCase__ )}], [{"""generated_text""": ANY(UpperCamelCase__ )}, {"""generated_text""": ANY(UpperCamelCase__ )}], ] , ) A_ = generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{"""generated_text""": ANY(UpperCamelCase__ )}, {"""generated_text""": ANY(UpperCamelCase__ )}], [{"""generated_text""": ANY(UpperCamelCase__ )}, {"""generated_text""": ANY(UpperCamelCase__ )}], ] , ) with self.assertRaises(UpperCamelCase__ ): generator(4 ) @require_torch def snake_case_ ( self ) -> Dict: '''simple docstring''' A_ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""" ) # do_sample=False necessary for reproducibility A_ = generator("""Something there""" , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{"""generated_text""": """"""}] ) A_ = 3 A_ = generator( """Something there""" , num_return_sequences=UpperCamelCase__ , num_beams=UpperCamelCase__ , ) A_ = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) A_ = generator("""This is a test""" , do_sample=UpperCamelCase__ , num_return_sequences=2 , return_tensors=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] , ) A_ = generator.model.config.eos_token_id A_ = """<pad>""" A_ = generator( ["""This is a test""", """This is a second test"""] , do_sample=UpperCamelCase__ , num_return_sequences=2 , batch_size=2 , return_tensors=UpperCamelCase__ , ) self.assertEqual( UpperCamelCase__ , [ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] , ) @require_tf def snake_case_ ( self ) -> Any: '''simple docstring''' A_ = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""" ) # do_sample=False necessary for reproducibility A_ = generator("""Something there""" , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{"""generated_text""": """"""}] )
162
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def lowercase (_A ): """simple docstring""" return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() ) def lowercase (_A , _A ): """simple docstring""" _lowerCAmelCase : List[str] = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue _lowerCAmelCase : int = key.replace('heads.cmd.mim_head.cls.predictions' , 'mmm_image_head' ) _lowerCAmelCase : str = key.replace('heads.cmd.mlm_head.cls.predictions' , 'mmm_text_head' ) _lowerCAmelCase : Optional[Any] = key.replace('heads.cmd.itm_head.cls' , 'itm_head' ) _lowerCAmelCase : str = key.replace('heads.cmd.itm_head.pooler' , 'itm_head.pooler' ) _lowerCAmelCase : List[str] = key.replace('heads.cmd.clip_head.logit_scale' , 'flava.logit_scale' ) _lowerCAmelCase : int = key.replace('heads.fairseq_mlm.cls.predictions' , 'mlm_head' ) _lowerCAmelCase : str = key.replace('heads.imagenet.mim_head.cls.predictions' , 'mim_head' ) _lowerCAmelCase : Dict = key.replace('mm_text_projection' , 'flava.text_to_mm_projection' ) _lowerCAmelCase : int = key.replace('mm_image_projection' , 'flava.image_to_mm_projection' ) _lowerCAmelCase : Optional[Any] = key.replace('image_encoder.module' , 'flava.image_model' ) _lowerCAmelCase : Tuple = key.replace('text_encoder.module' , 'flava.text_model' ) _lowerCAmelCase : int = key.replace('mm_encoder.module.encoder.cls_token' , 'flava.multimodal_model.cls_token' ) _lowerCAmelCase : int = key.replace('mm_encoder.module' , 'flava.multimodal_model' ) _lowerCAmelCase : Optional[int] = key.replace('text_projection' , 'flava.text_projection' ) _lowerCAmelCase : Dict = key.replace('image_projection' , 'flava.image_projection' ) _lowerCAmelCase : Tuple = value.float() for key, value in codebook_state_dict.items(): _lowerCAmelCase : str = value return upgrade @torch.no_grad() def lowercase (_A , _A , _A , _A=None ): """simple docstring""" if config_path is not None: _lowerCAmelCase : Optional[Any] = FlavaConfig.from_pretrained(_A ) else: _lowerCAmelCase : Optional[int] = FlavaConfig() _lowerCAmelCase : Optional[int] = FlavaForPreTraining(_A ).eval() _lowerCAmelCase : str = convert_dalle_checkpoint(_A , _A , save_checkpoint=_A ) if os.path.exists(_A ): _lowerCAmelCase : Optional[Any] = torch.load(_A , map_location='cpu' ) else: _lowerCAmelCase : Tuple = torch.hub.load_state_dict_from_url(_A , map_location='cpu' ) _lowerCAmelCase : List[Any] = upgrade_state_dict(_A , _A ) hf_model.load_state_dict(_A ) _lowerCAmelCase : str = hf_model.state_dict() _lowerCAmelCase : str = count_parameters(_A ) _lowerCAmelCase : Any = count_parameters(_A ) + count_parameters(_A ) assert torch.allclose(_A , _A , atol=1E-3 ) hf_model.save_pretrained(_A ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCAmelCase : Any = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
365
'''simple docstring''' import argparse import os import re lowerCAmelCase : Tuple = """src/transformers""" # Pattern that looks at the indentation in a line. lowerCAmelCase : str = re.compile(r"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. lowerCAmelCase : str = re.compile(r"""^\s*\"([^\"]+)\":""") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. lowerCAmelCase : Optional[int] = re.compile(r"""^\s*_import_structure\[\"([^\"]+)\"\]""") # Pattern that matches `"key",` and puts `key` in group 0. lowerCAmelCase : List[str] = re.compile(r"""^\s*\"([^\"]+)\",\s*$""") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. lowerCAmelCase : Optional[int] = re.compile(r"""\[([^\]]+)\]""") def lowercase (_A ): """simple docstring""" _lowerCAmelCase : int = _re_indent.search(_A ) return "" if search is None else search.groups()[0] def lowercase (_A , _A="" , _A=None , _A=None ): """simple docstring""" _lowerCAmelCase : int = 0 _lowerCAmelCase : Dict = code.split('\n' ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 _lowerCAmelCase : Dict = ['\n'.join(lines[:index] )] else: _lowerCAmelCase : str = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). _lowerCAmelCase : List[Any] = [lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ): current_block.append(lines[index] ) blocks.append('\n'.join(_A ) ) if index < len(_A ) - 1: _lowerCAmelCase : Union[str, Any] = [lines[index + 1]] index += 1 else: _lowerCAmelCase : Union[str, Any] = [] else: blocks.append('\n'.join(_A ) ) _lowerCAmelCase : List[str] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append('\n'.join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append('\n'.join(lines[index:] ) ) return blocks def lowercase (_A ): """simple docstring""" def _inner(_A ): return key(_A ).lower().replace('_' , '' ) return _inner def lowercase (_A , _A=None ): """simple docstring""" def noop(_A ): return x if key is None: _lowerCAmelCase : List[Any] = noop # Constants are all uppercase, they go first. _lowerCAmelCase : List[Any] = [obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. _lowerCAmelCase : Tuple = [obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. _lowerCAmelCase : List[str] = [obj for obj in objects if not key(_A )[0].isupper()] _lowerCAmelCase : Dict = ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def lowercase (_A ): """simple docstring""" def _replace(_A ): _lowerCAmelCase : Dict = match.groups()[0] if "," not in imports: return f'[{imports}]' _lowerCAmelCase : Union[str, Any] = [part.strip().replace('"' , '' ) for part in imports.split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _lowerCAmelCase : int = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]" _lowerCAmelCase : Tuple = import_statement.split('\n' ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. _lowerCAmelCase : Optional[Any] = 2 if lines[1].strip() == '[' else 1 _lowerCAmelCase : List[str] = [(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] _lowerCAmelCase : Dict = sort_objects(_A , key=lambda _A : x[1] ) _lowerCAmelCase : Tuple = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: _lowerCAmelCase : Tuple = _re_bracket_content.sub(_replace , lines[1] ) else: _lowerCAmelCase : Optional[Any] = [part.strip().replace('"' , '' ) for part in lines[1].split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _lowerCAmelCase : List[str] = keys[:-1] _lowerCAmelCase : Optional[Any] = get_indent(lines[1] ) + ', '.join([f'"{k}"' for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line _lowerCAmelCase : Union[str, Any] = _re_bracket_content.sub(_replace , _A ) return import_statement def lowercase (_A , _A=True ): """simple docstring""" with open(_A , encoding='utf-8' ) as f: _lowerCAmelCase : Any = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 _lowerCAmelCase : Tuple = split_code_in_indented_blocks( _A , start_prompt='_import_structure = {' , end_prompt='if TYPE_CHECKING:' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. _lowerCAmelCase : Tuple = main_blocks[block_idx] _lowerCAmelCase : int = block.split('\n' ) # Get to the start of the imports. _lowerCAmelCase : Tuple = 0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: _lowerCAmelCase : Dict = len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. _lowerCAmelCase : str = '\n'.join(block_lines[line_idx:-1] ) _lowerCAmelCase : Tuple = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. _lowerCAmelCase : List[Any] = split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend _lowerCAmelCase : Optional[int] = _re_direct_key if '_import_structure = {' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. _lowerCAmelCase : int = [(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. _lowerCAmelCase : Dict = [(i, key) for i, key in enumerate(_A ) if key is not None] _lowerCAmelCase : Optional[int] = [x[0] for x in sorted(_A , key=lambda _A : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. _lowerCAmelCase : int = 0 _lowerCAmelCase : Optional[Any] = [] for i in range(len(_A ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: _lowerCAmelCase : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. _lowerCAmelCase : Optional[int] = '\n'.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(_A , 'w' , encoding='utf-8' ) as f: f.write('\n'.join(_A ) ) def lowercase (_A=True ): """simple docstring""" _lowerCAmelCase : int = [] for root, _, files in os.walk(_A ): if "__init__.py" in files: _lowerCAmelCase : Optional[Any] = sort_imports(os.path.join(_A , '__init__.py' ) , check_only=_A ) if result: _lowerCAmelCase : Optional[int] = [os.path.join(_A , '__init__.py' )] if len(_A ) > 0: raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' ) if __name__ == "__main__": lowerCAmelCase : List[Any] = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") lowerCAmelCase : List[str] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
25
0
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class A ( unittest.TestCase ): def lowercase_ (self : Optional[int] ) -> Tuple: """simple docstring""" UpperCAmelCase__ = "hf-internal-testing/tiny-random-t5" UpperCAmelCase__ = AutoTokenizer.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = tokenizer("This is me" , return_tensors="pt" ) UpperCAmelCase__ = model.to_bettertransformer() self.assertTrue(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) UpperCAmelCase__ = model.generate(**__UpperCAmelCase ) UpperCAmelCase__ = model.reverse_bettertransformer() self.assertFalse(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any("BetterTransformer" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) UpperCAmelCase__ = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def lowercase_ (self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase__ = "hf-internal-testing/tiny-random-t5" UpperCAmelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
65
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model lowerCamelCase_ = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def __magic_name__ ( __a : Union[str, Any] , __a : Any , __a : Union[str, Any]=None ): '''simple docstring''' if rng is None: UpperCamelCase__ = random.Random() UpperCamelCase__ = 1 for dim in shape: total_dims *= dim UpperCamelCase__ = [] for _ in range(__a ): values.append(rng.randint(0 , vocab_size - 1 ) ) UpperCamelCase__ = np.array(__a , dtype=jnp.intaa ).reshape(__a ) return output def __magic_name__ ( __a : Dict , __a : Tuple=None ): '''simple docstring''' UpperCamelCase__ = ids_tensor(__a , vocab_size=2 , rng=__a ) # make sure that at least one token is attended to for each batch UpperCamelCase__ = 1 return attn_mask @require_flax class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = () def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 UpperCamelCase__ = 2 UpperCamelCase__ = inputs["""input_ids"""].shape[-1] // 2 UpperCamelCase__ = inputs["""input_ids"""][:max_batch_size, :sequence_length] UpperCamelCase__ = jnp.ones_like(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens UpperCamelCase__ = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` UpperCamelCase__ = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = False UpperCamelCase__ = max_length UpperCamelCase__ = 0 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning UpperCamelCase__ = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = pt_model_class(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE_ , flax_model.params ) UpperCamelCase__ = flax_model.generate(SCREAMING_SNAKE_CASE_ ).sequences UpperCamelCase__ = pt_model.generate(torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: UpperCamelCase__ = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = False UpperCamelCase__ = max_length for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = True UpperCamelCase__ = max_length for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = False UpperCamelCase__ = max_length UpperCamelCase__ = 2 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = False UpperCamelCase__ = max_length UpperCamelCase__ = 2 UpperCamelCase__ = 2 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = True UpperCamelCase__ = max_length UpperCamelCase__ = 0.8 UpperCamelCase__ = 10 UpperCamelCase__ = 0.3 UpperCamelCase__ = 1 UpperCamelCase__ = 8 UpperCamelCase__ = 9 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = max_length UpperCamelCase__ = 1 UpperCamelCase__ = 8 UpperCamelCase__ = 9 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() UpperCamelCase__ = max_length UpperCamelCase__ = 2 UpperCamelCase__ = 1 UpperCamelCase__ = 8 UpperCamelCase__ = 9 for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase__ = False UpperCamelCase__ = max_length for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase__ = True UpperCamelCase__ = max_length for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase__ = 2 UpperCamelCase__ = max_length for model_class in self.all_generative_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertEqual(generation_outputs.shape[-1] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jit(model.generate ) UpperCamelCase__ = jit_generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) UpperCamelCase__ = FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) UpperCamelCase__ = """Hello world""" UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , """do_samples""" ): model.generate(SCREAMING_SNAKE_CASE_ , do_samples=SCREAMING_SNAKE_CASE_ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , """foo""" ): UpperCamelCase__ = {"""foo""": """bar"""} model.generate(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
244
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 numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class _lowercase ( snake_case_ ): lowercase = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) lowercase = 'CIDAS/clipseg-rd64-refined' lowercase = 'image_segmenter' lowercase = CLIPSegForImageSegmentation lowercase = ['image', 'text'] lowercase = ['image'] def __init__( self : List[str] , *snake_case : int , **snake_case : Optional[int] ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['vision'] ) super().__init__(*snake_case , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : "Image" , snake_case : str ) -> Any: """simple docstring""" return self.pre_processor(text=[label] , images=[image] , padding=snake_case , return_tensors='pt' ) def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Optional[int] ) -> Tuple: """simple docstring""" with torch.no_grad(): UpperCamelCase_ : Any = self.model(**snake_case ).logits return logits def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : int ) -> int: """simple docstring""" UpperCamelCase_ : Union[str, Any] = outputs.cpu().detach().numpy() UpperCamelCase_ : str = 0 UpperCamelCase_ : List[Any] = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
50
from __future__ import annotations import numpy as np def __lowercase ( lowerCamelCase : list[float] ): return np.maximum(0 , lowerCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
50
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a_ : List[Any] = logging.get_logger(__name__) a_ : Dict = { "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json", # See all DPT models at https://huggingface.co/models?filter=dpt } class a ( _SCREAMING_SNAKE_CASE ): _lowerCAmelCase = """dpt""" def __init__( self , __magic_name__=7_68 , __magic_name__=12 , __magic_name__=12 , __magic_name__=30_72 , __magic_name__="gelu" , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.0_2 , __magic_name__=1e-12 , __magic_name__=3_84 , __magic_name__=16 , __magic_name__=3 , __magic_name__=False , __magic_name__=True , __magic_name__=[2, 5, 8, 11] , __magic_name__="project" , __magic_name__=[4, 2, 1, 0.5] , __magic_name__=[96, 1_92, 3_84, 7_68] , __magic_name__=2_56 , __magic_name__=-1 , __magic_name__=False , __magic_name__=True , __magic_name__=0.4 , __magic_name__=2_55 , __magic_name__=0.1 , __magic_name__=[1, 10_24, 24, 24] , __magic_name__=[0, 1] , __magic_name__=None , **__magic_name__ , ) -> Dict: super().__init__(**__magic_name__ ) _a = hidden_size _a = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) _a = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } _a = BitConfig(**__magic_name__ ) elif isinstance(__magic_name__ , __magic_name__ ): logger.info('Initializing the config with a `BiT` backbone.' ) _a = BitConfig(**__magic_name__ ) elif isinstance(__magic_name__ , __magic_name__ ): _a = backbone_config else: raise ValueError( f'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) _a = backbone_featmap_shape _a = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: _a = None _a = None _a = [] _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 = image_size _a = patch_size _a = num_channels _a = qkv_bias _a = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) _a = readout_type _a = reassemble_factors _a = neck_hidden_sizes _a = fusion_hidden_size _a = head_in_index _a = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) _a = use_auxiliary_head _a = auxiliary_loss_weight _a = semantic_loss_ignore_index _a = semantic_classifier_dropout def __UpperCAmelCase ( self ) -> Optional[Any]: _a = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: _a = self.backbone_config.to_dict() _a = self.__class__.model_type return output
168
'''simple docstring''' import numpy as np class a : def __init__( self ) -> List[str]: _a = (0, 0) _a = None _a = 0 _a = 0 _a = 0 def __eq__( self , __magic_name__ ) -> Optional[int]: return self.position == cell.position def __UpperCAmelCase ( self ) -> Any: print(self.position ) class a : def __init__( self , __magic_name__=(5, 5) ) -> Optional[int]: _a = np.zeros(__magic_name__ ) _a = world_size[0] _a = world_size[1] def __UpperCAmelCase ( self ) -> List[Any]: print(self.w ) def __UpperCAmelCase ( self , __magic_name__ ) -> Union[str, Any]: _a = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] _a = cell.position[0] _a = cell.position[1] _a = [] for n in neughbour_cord: _a = current_x + n[0] _a = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: _a = Cell() _a = (x, y) _a = cell neighbours.append(__magic_name__ ) return neighbours def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :Union[str, Any] , lowerCAmelCase__ :int ) -> List[str]: '''simple docstring''' _a = [] _a = [] _open.append(lowerCAmelCase__ ) while _open: _a = np.argmin([n.f for n in _open] ) _a = _open[min_f] _closed.append(_open.pop(lowerCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(lowerCAmelCase__ ): for c in _closed: if c == n: continue _a = current.g + 1 _a , _a = n.position _a , _a = goal.position _a = (ya - ya) ** 2 + (xa - xa) ** 2 _a = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(lowerCAmelCase__ ) _a = [] while current.parent is not None: path.append(current.position ) _a = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": a_ : str = Gridworld() # Start position and goal a_ : str = Cell() a_ : Dict = (0, 0) a_ : Dict = Cell() a_ : Optional[Any] = (4, 4) print(f'''path from {start.position} to {goal.position}''') a_ : Tuple = astar(world, start, goal) # Just for visual reasons. for i in s: a_ : Any = 1 print(world.w)
168
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Optional[Any] = { 'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LlamaConfig'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = ['LlamaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = ['LlamaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Tuple = [ 'LlamaForCausalLM', 'LlamaModel', 'LlamaPreTrainedModel', 'LlamaForSequenceClassification', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys UpperCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
357
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function UpperCAmelCase_ : str = 1.054571817e-34 # unit of ℏ : J * s UpperCAmelCase_ : Dict = 3e8 # unit of c : m * s^-1 def SCREAMING_SNAKE_CASE_ ( __A : float , __A : float , __A : float ) -> dict[str, float]: """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if force < 0: raise ValueError('Magnitude of force can not be negative' ) if distance < 0: raise ValueError('Distance can not be negative' ) if area < 0: raise ValueError('Area can not be negative' ) if force == 0: a_ : Optional[Any] = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_40 * (distance) ** 4 ) return {"force": force} elif area == 0: a_ : List[str] = (2_40 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: a_ : Tuple = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_40 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('One and only one argument must be 0' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
120
0
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __snake_case =16 __snake_case =32 def a_ ( lowerCamelCase : Accelerator , lowerCamelCase : DatasetDict , lowerCamelCase : List[int] , lowerCamelCase : List[int] , lowerCamelCase : int = 16 ): lowerCAmelCase = AutoTokenizer.from_pretrained('bert-base-cased' ) lowerCAmelCase = DatasetDict( { 'train': dataset['train'].select(lowerCamelCase ), 'validation': dataset['train'].select(lowerCamelCase ), 'test': dataset['validation'], } ) def tokenize_function(lowerCamelCase : str ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCamelCase , max_length=lowerCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase = datasets.map( lowerCamelCase , batched=lowerCamelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowerCamelCase : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase = 8 else: lowerCAmelCase = None return tokenizer.pad( lowerCamelCase , padding='longest' , max_length=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_tensors='pt' , ) # Instantiate dataloaders. lowerCAmelCase = DataLoader( tokenized_datasets['train'] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) lowerCAmelCase = DataLoader( tokenized_datasets['validation'] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) lowerCAmelCase = DataLoader( tokenized_datasets['test'] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) return train_dataloader, eval_dataloader, test_dataloader def a_ ( lowerCamelCase : Tuple , lowerCamelCase : List[Any] ): # New Code # lowerCAmelCase = [] # Download the dataset lowerCAmelCase = load_dataset('glue' , 'mrpc' ) # Create our splits lowerCAmelCase = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator lowerCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase = config['lr'] lowerCAmelCase = int(config['num_epochs'] ) lowerCAmelCase = int(config['seed'] ) lowerCAmelCase = int(config['batch_size'] ) lowerCAmelCase = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation lowerCAmelCase = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: lowerCAmelCase = batch_size // MAX_GPU_BATCH_SIZE lowerCAmelCase = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase ) # New Code # # Create our folds: lowerCAmelCase = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) lowerCAmelCase = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(lowerCamelCase ): lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = get_fold_dataloaders( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=lowerCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase = AdamW(params=model.parameters() , lr=lowerCamelCase ) # Instantiate scheduler lowerCAmelCase = get_linear_schedule_with_warmup( optimizer=lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = accelerator.prepare( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Now we train the model for epoch in range(lowerCamelCase ): model.train() for step, batch in enumerate(lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCAmelCase = model(**lowerCamelCase ) lowerCAmelCase = outputs.loss lowerCAmelCase = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase = model(**lowerCamelCase ) lowerCAmelCase = outputs.logits.argmax(dim=-1 ) lowerCAmelCase , lowerCAmelCase = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCamelCase , references=lowerCamelCase , ) lowerCAmelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCamelCase ) # New Code # # We also run predictions on the test set at the very end lowerCAmelCase = [] for step, batch in enumerate(lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase = model(**lowerCamelCase ) lowerCAmelCase = outputs.logits lowerCAmelCase , lowerCAmelCase = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(lowerCamelCase , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: lowerCAmelCase = torch.cat(lowerCamelCase , dim=0 ) lowerCAmelCase = torch.stack(lowerCamelCase , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) lowerCAmelCase = metric.compute(predictions=lowerCamelCase , references=lowerCamelCase ) accelerator.print('Average test metrics from all folds:' , lowerCamelCase ) def a_ ( ): lowerCAmelCase = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=lowerCamelCase , default=lowerCamelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=lowerCamelCase , default=3 , help='The number of splits to perform across the dataset' ) lowerCAmelCase = parser.parse_args() lowerCAmelCase = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCamelCase , lowerCamelCase ) if __name__ == "__main__": main()
4
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : int ) -> None: SCREAMING_SNAKE_CASE__ : List[Any] =value SCREAMING_SNAKE_CASE__ : Node | None =None SCREAMING_SNAKE_CASE__ : Node | None =None class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , __lowercase : Node ) -> None: SCREAMING_SNAKE_CASE__ : Any =tree def __magic_name__ ( self : str , __lowercase : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : Union[str, Any] ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
152
0
"""simple docstring""" import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json UpperCamelCase = '''sshleifer/mar_enro_6_3_student''' class __UpperCAmelCase (_snake_case ): def UpperCamelCase ( self: Dict ): '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE = cached_path( """https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz""" , extract_compressed_file=UpperCamelCase__ , ) _SCREAMING_SNAKE_CASE = F'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def UpperCamelCase ( self: Any ): '''simple docstring''' MarianMTModel.from_pretrained(UpperCamelCase__ ) @slow @require_torch_gpu def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = { """$MAX_LEN""": 64, """$BS""": 64, """$GAS""": 1, """$ENRO_DIR""": self.data_dir, """facebook/mbart-large-cc25""": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", """--learning_rate=3e-5""": """--learning_rate 3e-4""", """--num_train_epochs 6""": """--num_train_epochs 1""", } # Clean up bash script _SCREAMING_SNAKE_CASE = (self.test_file_dir / """train_mbart_cc25_enro.sh""").open().read().split("""finetune.py""" )[1].strip() _SCREAMING_SNAKE_CASE = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) for k, v in env_vars_to_replace.items(): _SCREAMING_SNAKE_CASE = bash_script.replace(UpperCamelCase__ , str(UpperCamelCase__ ) ) _SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") _SCREAMING_SNAKE_CASE = F'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future _SCREAMING_SNAKE_CASE = ["""finetune.py"""] + bash_script.split() + args with patch.object(UpperCamelCase__ , """argv""" , UpperCamelCase__ ): _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() _SCREAMING_SNAKE_CASE = pl.Trainer.add_argparse_args(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = SummarizationModule.add_model_specific_args(UpperCamelCase__ , os.getcwd() ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = main(UpperCamelCase__ ) # Check metrics _SCREAMING_SNAKE_CASE = load_json(model.metrics_save_path ) _SCREAMING_SNAKE_CASE = metrics["""val"""][0] _SCREAMING_SNAKE_CASE = metrics["""val"""][-1] self.assertEqual(len(metrics["""val"""] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[F'val_avg_{model.val_metric}'] , UpperCamelCase__ ) self.assertGreater(last_step_stats["""val_avg_gen_time"""] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["""val_avg_gen_time"""] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["""val_avg_bleu"""] - first_step_stats["""val_avg_bleu"""] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["""val_avg_bleu"""] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["""val"""][-1]["""val_avg_bleu"""] - metrics["""test"""][-1]["""test_avg_bleu"""] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict _SCREAMING_SNAKE_CASE = os.listdir(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = [x for x in contents if x.endswith(""".ckpt""" )][0] _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = torch.load(UpperCamelCase__ , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _SCREAMING_SNAKE_CASE = {os.path.basename(UpperCamelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1 class __UpperCAmelCase (_snake_case ): @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def UpperCamelCase ( self: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = F'{self.test_file_dir_str}/test_data/wmt_en_ro' _SCREAMING_SNAKE_CASE = { """--fp16_opt_level=O1""": """""", """$MAX_LEN""": 128, """$BS""": 16, """$GAS""": 1, """$ENRO_DIR""": data_dir, """$m""": """sshleifer/student_marian_en_ro_6_1""", """val_check_interval=0.25""": """val_check_interval=1.0""", } # Clean up bash script _SCREAMING_SNAKE_CASE = ( (self.test_file_dir / """distil_marian_no_teacher.sh""").open().read().split("""distillation.py""" )[1].strip() ) _SCREAMING_SNAKE_CASE = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) _SCREAMING_SNAKE_CASE = bash_script.replace("""--fp16 """ , """ """ ) for k, v in env_vars_to_replace.items(): _SCREAMING_SNAKE_CASE = bash_script.replace(UpperCamelCase__ , str(UpperCamelCase__ ) ) _SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE = bash_script.replace("""--fp16""" , """""" ) _SCREAMING_SNAKE_CASE = 6 _SCREAMING_SNAKE_CASE = ( ["""distillation.py"""] + bash_script.split() + [ F'--output_dir={output_dir}', """--gpus=1""", """--learning_rate=1e-3""", F'--num_train_epochs={epochs}', """--warmup_steps=10""", """--val_check_interval=1.0""", """--do_predict""", ] ) with patch.object(UpperCamelCase__ , """argv""" , UpperCamelCase__ ): _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() _SCREAMING_SNAKE_CASE = pl.Trainer.add_argparse_args(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = SummarizationDistiller.add_model_specific_args(UpperCamelCase__ , os.getcwd() ) _SCREAMING_SNAKE_CASE = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu _SCREAMING_SNAKE_CASE = distill_main(UpperCamelCase__ ) # Check metrics _SCREAMING_SNAKE_CASE = load_json(model.metrics_save_path ) _SCREAMING_SNAKE_CASE = metrics["""val"""][0] _SCREAMING_SNAKE_CASE = metrics["""val"""][-1] assert len(metrics["""val"""] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[F'val_avg_{model.val_metric}'] , UpperCamelCase__ ) # check lightning ckpt can be loaded and has a reasonable statedict _SCREAMING_SNAKE_CASE = os.listdir(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = [x for x in contents if x.endswith(""".ckpt""" )][0] _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = torch.load(UpperCamelCase__ , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _SCREAMING_SNAKE_CASE = {os.path.basename(UpperCamelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1
363
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ = 1_60_00 ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE = int(round(sample_rate * max_length ) ) if len(snake_case__ ) <= sample_length: return wav _SCREAMING_SNAKE_CASE = randint(0 ,len(snake_case__ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __UpperCAmelCase : __snake_case : Optional[str] = field(default=_UpperCAmelCase ,metadata={"help": "Name of a dataset from the datasets package"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the training audio paths and labels."} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "A file containing the validation audio paths and labels."} ) __snake_case : str = field( default="train" ,metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } ,) __snake_case : str = field( default="validation" ,metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } ,) __snake_case : str = field( default="audio" ,metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} ,) __snake_case : str = field( default="label" ,metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) __snake_case : Optional[int] = field( default=_UpperCAmelCase ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } ,) __snake_case : float = field( default=20 ,metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} ,) @dataclass class __UpperCAmelCase : __snake_case : str = field( default="facebook/wav2vec2-base" ,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) __snake_case : str = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) __snake_case : Optional[str] = field( default=_UpperCAmelCase ,metadata={"help": "Name or path of preprocessor config."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) __snake_case : Optional[bool] = field( default=_UpperCAmelCase ,metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) __snake_case : bool = field( default=_UpperCAmelCase ,metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} ,) def UpperCamelCase ( self: List[str] ): '''simple docstring''' if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( """The argument `--freeze_feature_extractor` is deprecated and """ """will be removed in a future version. Use `--freeze_feature_encoder`""" """instead. Setting `freeze_feature_encoder==True`.""" , UpperCAmelCase_ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( """The argument `--freeze_feature_extractor` is deprecated and """ """should not be used in combination with `--freeze_feature_encoder`.""" """Only make use of `--freeze_feature_encoder`.""" ) def __lowerCamelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_audio_classification""" ,snake_case__ ,snake_case__ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to train from scratch.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset and prepare it for the audio classification task. _SCREAMING_SNAKE_CASE = DatasetDict() _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--audio_column_name` to the correct audio column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ' """Make sure to set `--label_column_name` to the correct text column - one of """ F'{", ".join(raw_datasets["train"].column_names )}.' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _SCREAMING_SNAKE_CASE = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _SCREAMING_SNAKE_CASE = feature_extractor.model_input_names[0] def train_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [] for audio in batch[data_args.audio_column_name]: _SCREAMING_SNAKE_CASE = random_subsample( audio["""array"""] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(snake_case__ ) _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(snake_case__ ): _SCREAMING_SNAKE_CASE = [audio["""array"""] for audio in batch[data_args.audio_column_name]] _SCREAMING_SNAKE_CASE = feature_extractor(snake_case__ ,sampling_rate=feature_extractor.sampling_rate ) _SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(snake_case__ )} _SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _SCREAMING_SNAKE_CASE = raw_datasets["""train"""].features[data_args.label_column_name].names _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = {}, {} for i, label in enumerate(snake_case__ ): _SCREAMING_SNAKE_CASE = str(snake_case__ ) _SCREAMING_SNAKE_CASE = label # Load the accuracy metric from the datasets package _SCREAMING_SNAKE_CASE = evaluate.load("""accuracy""" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(snake_case__ ): _SCREAMING_SNAKE_CASE = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=snake_case__ ,references=eval_pred.label_ids ) _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(snake_case__ ) ,labelaid=snake_case__ ,idalabel=snake_case__ ,finetuning_task="""audio-classification""" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _SCREAMING_SNAKE_CASE = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=snake_case__ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) if training_args.do_eval: if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE = ( raw_datasets["""eval"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(snake_case__ ,output_all_columns=snake_case__ ) # Initialize our trainer _SCREAMING_SNAKE_CASE = Trainer( model=snake_case__ ,args=snake_case__ ,train_dataset=raw_datasets["""train"""] if training_args.do_train else None ,eval_dataset=raw_datasets["""eval"""] if training_args.do_eval else None ,compute_metrics=snake_case__ ,tokenizer=snake_case__ ,) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE = last_checkpoint _SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics("""train""" ,train_result.metrics ) trainer.save_metrics("""train""" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE = trainer.evaluate() trainer.log_metrics("""eval""" ,snake_case__ ) trainer.save_metrics("""eval""" ,snake_case__ ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """audio-classification""", """dataset""": data_args.dataset_name, """tags""": ["""audio-classification"""], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) if __name__ == "__main__": main()
125
0
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowerCamelCase : List[str] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( lowercase : Tuple , lowercase : Optional[int] , lowercase : Optional[int] ): '''simple docstring''' return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def _SCREAMING_SNAKE_CASE ( lowercase : np.ndarray , lowercase : Optional[str] , lowercase : Optional[str] ): '''simple docstring''' lowerCamelCase_ = to_pil_image(lowercase ) lowerCamelCase_ , lowerCamelCase_ = pil_image.size lowerCamelCase_ = pytesseract.image_to_data(lowercase , lang=lowercase , output_type='dict' , config=lowercase ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates lowerCamelCase_ = [idx for idx, word in enumerate(lowercase ) if not word.strip()] lowerCamelCase_ = [word for idx, word in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] lowerCamelCase_ = [coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format lowerCamelCase_ = [] for x, y, w, h in zip(lowercase , lowercase , lowercase , lowercase ): lowerCamelCase_ = [x, y, x + w, y + h] actual_boxes.append(lowercase ) # finally, normalize the bounding boxes lowerCamelCase_ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase , lowercase , lowercase ) ) assert len(lowercase ) == len(lowercase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = ['''pixel_values'''] def __init__( self : int , A_ : bool = True , A_ : Dict[str, int] = None , A_ : PILImageResampling = PILImageResampling.BILINEAR , A_ : bool = True , A_ : float = 1 / 255 , A_ : bool = True , A_ : Union[float, Iterable[float]] = None , A_ : Union[float, Iterable[float]] = None , A_ : bool = True , A_ : Optional[str] = None , A_ : Optional[str] = "" , **A_ : Optional[int] , ) -> None: """simple docstring""" super().__init__(**A_ ) lowerCamelCase_ = size if size is not None else {'height': 224, 'width': 224} lowerCamelCase_ = get_size_dict(A_ ) lowerCamelCase_ = do_resize lowerCamelCase_ = size lowerCamelCase_ = resample lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_value lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD lowerCamelCase_ = apply_ocr lowerCamelCase_ = ocr_lang lowerCamelCase_ = tesseract_config def a__ ( self : str , A_ : np.ndarray , A_ : Dict[str, int] , A_ : PILImageResampling = PILImageResampling.BILINEAR , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : str , ) -> np.ndarray: """simple docstring""" lowerCamelCase_ = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) lowerCamelCase_ = (size['height'], size['width']) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def a__ ( self : Any , A_ : np.ndarray , A_ : Union[int, float] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Optional[Any] , ) -> np.ndarray: """simple docstring""" return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def a__ ( self : Union[str, Any] , A_ : np.ndarray , A_ : Union[float, Iterable[float]] , A_ : Union[float, Iterable[float]] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : int , ) -> np.ndarray: """simple docstring""" return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def a__ ( self : List[Any] , A_ : ImageInput , A_ : bool = None , A_ : Dict[str, int] = None , A_ : Dict=None , A_ : bool = None , A_ : float = None , A_ : bool = None , A_ : Union[float, Iterable[float]] = None , A_ : Union[float, Iterable[float]] = None , A_ : bool = None , A_ : Optional[str] = None , A_ : Optional[str] = None , A_ : Optional[Union[str, TensorType]] = None , A_ : ChannelDimension = ChannelDimension.FIRST , **A_ : Any , ) -> PIL.Image.Image: """simple docstring""" lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = size if size is not None else self.size lowerCamelCase_ = get_size_dict(A_ ) lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ = image_std if image_std is not None else self.image_std lowerCamelCase_ = apply_ocr if apply_ocr is not None else self.apply_ocr lowerCamelCase_ = ocr_lang if ocr_lang is not None else self.ocr_lang lowerCamelCase_ = tesseract_config if tesseract_config is not None else self.tesseract_config lowerCamelCase_ = make_list_of_images(A_ ) if not valid_images(A_ ): 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_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('If do_normalize is True, image_mean and image_std must be specified.' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(A_ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , 'pytesseract' ) lowerCamelCase_ = [] lowerCamelCase_ = [] for image in images: lowerCamelCase_ , lowerCamelCase_ = apply_tesseract(A_ , A_ , A_ ) words_batch.append(A_ ) boxes_batch.append(A_ ) if do_resize: lowerCamelCase_ = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(A_ , A_ ) for image in images] lowerCamelCase_ = BatchFeature(data={'pixel_values': images} , tensor_type=A_ ) if apply_ocr: lowerCamelCase_ = words_batch lowerCamelCase_ = boxes_batch return data
204
from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A( UpperCamelCase ): '''simple docstring''' def __init__( self : str , A_ : TransformeraDModel , A_ : AutoencoderKL , A_ : KarrasDiffusionSchedulers , A_ : Optional[Dict[int, str]] = None , ) -> str: """simple docstring""" super().__init__() self.register_modules(transformer=A_ , vae=A_ , scheduler=A_ ) # create a imagenet -> id dictionary for easier use lowerCamelCase_ = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(',' ): lowerCamelCase_ = int(A_ ) lowerCamelCase_ = dict(sorted(self.labels.items() ) ) def a__ ( self : Optional[int] , A_ : Union[str, List[str]] ) -> List[int]: """simple docstring""" if not isinstance(A_ , A_ ): lowerCamelCase_ = list(A_ ) for l in label: if l not in self.labels: raise ValueError( f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""" ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self : Any , A_ : List[int] , A_ : float = 4.0 , A_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A_ : int = 50 , A_ : Optional[str] = "pil" , A_ : bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" lowerCamelCase_ = len(A_ ) lowerCamelCase_ = self.transformer.config.sample_size lowerCamelCase_ = self.transformer.config.in_channels lowerCamelCase_ = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=A_ , device=self.device , dtype=self.transformer.dtype , ) lowerCamelCase_ = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents lowerCamelCase_ = torch.tensor(A_ , device=self.device ).reshape(-1 ) lowerCamelCase_ = torch.tensor([1000] * batch_size , device=self.device ) lowerCamelCase_ = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: lowerCamelCase_ = latent_model_input[: len(A_ ) // 2] lowerCamelCase_ = torch.cat([half, half] , dim=0 ) lowerCamelCase_ = self.scheduler.scale_model_input(A_ , A_ ) lowerCamelCase_ = t if not torch.is_tensor(A_ ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) lowerCamelCase_ = latent_model_input.device.type == 'mps' if isinstance(A_ , A_ ): lowerCamelCase_ = torch.floataa if is_mps else torch.floataa else: lowerCamelCase_ = torch.intaa if is_mps else torch.intaa lowerCamelCase_ = torch.tensor([timesteps] , dtype=A_ , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: lowerCamelCase_ = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML lowerCamelCase_ = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output lowerCamelCase_ = self.transformer( A_ , timestep=A_ , class_labels=A_ ).sample # perform guidance if guidance_scale > 1: lowerCamelCase_ , lowerCamelCase_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] lowerCamelCase_ , lowerCamelCase_ = torch.split(A_ , len(A_ ) // 2 , dim=0 ) lowerCamelCase_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps) lowerCamelCase_ = torch.cat([half_eps, half_eps] , dim=0 ) lowerCamelCase_ = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: lowerCamelCase_ , lowerCamelCase_ = torch.split(A_ , A_ , dim=1 ) else: lowerCamelCase_ = noise_pred # compute previous image: x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(A_ , A_ , A_ ).prev_sample if guidance_scale > 1: lowerCamelCase_ , lowerCamelCase_ = latent_model_input.chunk(2 , dim=0 ) else: lowerCamelCase_ = latent_model_input lowerCamelCase_ = 1 / self.vae.config.scaling_factor * latents lowerCamelCase_ = self.vae.decode(A_ ).sample lowerCamelCase_ = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(A_ ) if not return_dict: return (samples,) return ImagePipelineOutput(images=A_ )
204
1
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = [ 'decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase , __lowerCamelCase : Optional[Any] = emb.weight.shape __lowerCamelCase : int = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = emb.weight.data return lin_layer def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' ) __lowerCamelCase : Any = Namespace(**checkpoint['cfg']['model'] ) __lowerCamelCase : Dict = checkpoint['model'] remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = state_dict['decoder.embed_tokens.weight'].shape[0] __lowerCamelCase : int = {key.replace('decoder' , 'model' ): val for key, val in state_dict.items()} __lowerCamelCase : Any = XGLMConfig( vocab_size=SCREAMING_SNAKE_CASE__ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='gelu' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) __lowerCamelCase : List[Any] = XGLMForCausalLM(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowercase_ = parser.parse_args() lowercase_ = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
194
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration lowercase_ = 5_0_0_0_0 lowercase_ = 5_0_0_0 lowercase_ ,lowercase_ = os.path.split(__file__) lowercase_ = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = dataset[i : i + batch_size] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = dataset[i : i + batch_size] def UpperCamelCase__ ( ): __lowerCamelCase : Union[str, Any] = {'num examples': SPEED_TEST_N_EXAMPLES} __lowerCamelCase : Optional[Any] = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted, {'type': 'pandas', 'length': SMALL_TEST}), (read_formatted, {'type': 'torch', 'length': SMALL_TEST}), (read_formatted, {'type': 'tensorflow', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] __lowerCamelCase : Any = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('generating dataset' ) __lowerCamelCase : Optional[int] = datasets.Features( {'list': datasets.Sequence(datasets.Value('float32' ) ), 'numbers': datasets.Value('float32' )} ) __lowerCamelCase : str = generate_example_dataset( os.path.join(SCREAMING_SNAKE_CASE__ , 'dataset.arrow' ) , SCREAMING_SNAKE_CASE__ , num_examples=SCREAMING_SNAKE_CASE__ , seq_shapes={'list': (100,)} , ) print('first set of iterations' ) for func, kwargs in functions: print(func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[int] = func(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) print('shuffling dataset' ) __lowerCamelCase : str = dataset.shuffle() print('Second set of iterations (after shuffling' ) for func, kwargs in functions_shuffled: print('shuffled ' , func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : int = func( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
194
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable def lowercase ( _snake_case : Callable[[int | float], int | float] , _snake_case : int | float , _snake_case : int | float , _snake_case : int = 100 , ) ->float: """simple docstring""" __snake_case : Tuple = x_start __snake_case : List[Any] = fnc(_snake_case ) __snake_case : Tuple = 0.0 for _ in range(_snake_case ): # Approximates small segments of curve as linear and solve # for trapezoidal area __snake_case : Any = (x_end - x_start) / steps + xa __snake_case : int = fnc(_snake_case ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __snake_case : Any = xa __snake_case : str = fxa return area if __name__ == "__main__": def lowercase ( _snake_case : Optional[int] ) ->int: """simple docstring""" return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") SCREAMING_SNAKE_CASE : Tuple = 10 while i <= 10_0000: print(F'with {i} steps: {trapezoidal_area(f, -5, 5, i)}') i *= 10
102
"""simple docstring""" def lowercase_ ( _snake_case ,_snake_case ): return 1 if input_a == input_a else 0 def lowercase_ ( ): assert xnor_gate(0 ,0 ) == 1 assert xnor_gate(0 ,1 ) == 0 assert xnor_gate(1 ,0 ) == 0 assert xnor_gate(1 ,1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
25
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( __snake_case , unittest.TestCase ): lowercase = DiTPipeline lowercase = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS lowercase = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } lowercase = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS lowercase = False def UpperCAmelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) __UpperCamelCase = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=lowerCamelCase_ , activation_fn='gelu-approximate' , num_embeds_ada_norm=1000 , norm_type='ada_norm_zero' , norm_elementwise_affine=lowerCamelCase_ , ) __UpperCamelCase = AutoencoderKL() __UpperCamelCase = DDIMScheduler() __UpperCamelCase = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=0 ): '''simple docstring''' if str(lowerCamelCase_ ).startswith('mps' ): __UpperCamelCase = torch.manual_seed(lowerCamelCase_ ) else: __UpperCamelCase = torch.Generator(device=lowerCamelCase_ ).manual_seed(lowerCamelCase_ ) __UpperCamelCase = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = """cpu""" __UpperCamelCase = self.get_dummy_components() __UpperCamelCase = self.pipeline_class(**lowerCamelCase_ ) pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) __UpperCamelCase = self.get_dummy_inputs(lowerCamelCase_ ) __UpperCamelCase = pipe(**lowerCamelCase_ ).images __UpperCamelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __UpperCamelCase = np.array([0.2_9_4_6, 0.6_6_0_1, 0.4_3_2_9, 0.3_2_9_6, 0.4_1_4_4, 0.5_3_1_9, 0.7_2_7_3, 0.5_0_1_3, 0.4_4_5_7] ) __UpperCamelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase_ , 1E-3 ) def UpperCAmelCase ( self ): '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=lowerCamelCase_ , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCAmelCase ( self ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class __lowerCAmelCase ( unittest.TestCase ): def UpperCAmelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = torch.manual_seed(0 ) __UpperCamelCase = DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __UpperCamelCase = ["""vase""", """umbrella""", """white shark""", """white wolf"""] __UpperCamelCase = pipe.get_label_ids(lowerCamelCase_ ) __UpperCamelCase = pipe(lowerCamelCase_ , generator=lowerCamelCase_ , num_inference_steps=40 , output_type='np' ).images for word, image in zip(lowerCamelCase_ , lowerCamelCase_ ): __UpperCamelCase = load_numpy( F'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1E-2 def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __UpperCamelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __UpperCamelCase = ["""vase""", """umbrella"""] __UpperCamelCase = pipe.get_label_ids(lowerCamelCase_ ) __UpperCamelCase = torch.manual_seed(0 ) __UpperCamelCase = pipe(lowerCamelCase_ , generator=lowerCamelCase_ , num_inference_steps=25 , output_type='np' ).images for word, image in zip(lowerCamelCase_ , lowerCamelCase_ ): __UpperCamelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' F'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1E-1
365
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : str = logging.get_logger(__name__) UpperCamelCase : Dict = { "microsoft/wavlm-base": "https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): lowercase = "wavlm" def __init__( self , __UpperCAmelCase=32 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.0_2 , __UpperCAmelCase=1E-5 , __UpperCAmelCase="group" , __UpperCAmelCase="gelu" , __UpperCAmelCase=(512, 512, 512, 512, 512, 512, 512) , __UpperCAmelCase=(5, 2, 2, 2, 2, 2, 2) , __UpperCAmelCase=(10, 3, 3, 3, 3, 2, 2) , __UpperCAmelCase=False , __UpperCAmelCase=128 , __UpperCAmelCase=16 , __UpperCAmelCase=320 , __UpperCAmelCase=800 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.0_5 , __UpperCAmelCase=10 , __UpperCAmelCase=2 , __UpperCAmelCase=0.0 , __UpperCAmelCase=10 , __UpperCAmelCase=320 , __UpperCAmelCase=2 , __UpperCAmelCase=0.1 , __UpperCAmelCase=100 , __UpperCAmelCase=256 , __UpperCAmelCase=256 , __UpperCAmelCase=0.1 , __UpperCAmelCase="mean" , __UpperCAmelCase=False , __UpperCAmelCase=False , __UpperCAmelCase=256 , __UpperCAmelCase=(512, 512, 512, 512, 1500) , __UpperCAmelCase=(5, 3, 3, 1, 1) , __UpperCAmelCase=(1, 2, 3, 1, 1) , __UpperCAmelCase=512 , __UpperCAmelCase=80 , __UpperCAmelCase=0 , __UpperCAmelCase=1 , __UpperCAmelCase=2 , __UpperCAmelCase=False , __UpperCAmelCase=3 , __UpperCAmelCase=2 , __UpperCAmelCase=3 , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase , pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase ) __UpperCamelCase = hidden_size __UpperCamelCase = feat_extract_norm __UpperCamelCase = feat_extract_activation __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = conv_bias __UpperCamelCase = num_buckets __UpperCamelCase = max_bucket_distance __UpperCamelCase = num_conv_pos_embeddings __UpperCamelCase = num_conv_pos_embedding_groups __UpperCamelCase = len(self.conv_dim ) __UpperCamelCase = num_hidden_layers __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_dropout __UpperCamelCase = attention_dropout __UpperCamelCase = activation_dropout __UpperCamelCase = feat_proj_dropout __UpperCamelCase = final_dropout __UpperCamelCase = layerdrop __UpperCamelCase = layer_norm_eps __UpperCamelCase = initializer_range __UpperCamelCase = num_ctc_classes __UpperCamelCase = vocab_size __UpperCamelCase = do_stable_layer_norm __UpperCamelCase = use_weighted_layer_sum __UpperCamelCase = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' F' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' F' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __UpperCamelCase = apply_spec_augment __UpperCamelCase = mask_time_prob __UpperCamelCase = mask_time_length __UpperCamelCase = mask_time_min_masks __UpperCamelCase = mask_feature_prob __UpperCamelCase = mask_feature_length # parameters for pretraining with codevector quantized representations __UpperCamelCase = num_codevectors_per_group __UpperCamelCase = num_codevector_groups __UpperCamelCase = contrastive_logits_temperature __UpperCamelCase = num_negatives __UpperCamelCase = codevector_dim __UpperCamelCase = proj_codevector_dim __UpperCamelCase = diversity_loss_weight # ctc loss __UpperCamelCase = ctc_loss_reduction __UpperCamelCase = ctc_zero_infinity # adapter __UpperCamelCase = add_adapter __UpperCamelCase = adapter_kernel_size __UpperCamelCase = adapter_stride __UpperCamelCase = num_adapter_layers __UpperCamelCase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCamelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = list(__UpperCAmelCase ) __UpperCamelCase = xvector_output_dim @property def UpperCAmelCase ( self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
263
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github __lowerCAmelCase = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __SCREAMING_SNAKE_CASE ( ): _snake_case = Github(os.environ["""GITHUB_TOKEN"""] ) _snake_case = g.get_repo("""huggingface/diffusers""" ) _snake_case = repo.get_issues(state="""open""" ) for issue in open_issues: _snake_case = sorted(issue.get_comments() , key=lambda _SCREAMING_SNAKE_CASE : i.created_at , reverse=_SCREAMING_SNAKE_CASE ) _snake_case = comments[0] if len(_SCREAMING_SNAKE_CASE ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
341
'''simple docstring''' import os from typing import Dict, List, Tuple, TypeVar, Union __lowerCAmelCase = TypeVar('T') __lowerCAmelCase = Union[List[T], Tuple[T, ...]] __lowerCAmelCase = Union[T, List[T], Dict[str, T]] __lowerCAmelCase = Union[str, bytes, os.PathLike]
341
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase_ : str = [ """EAGER""", """AOT_EAGER""", """INDUCTOR""", """NVFUSER""", """AOT_NVFUSER""", """AOT_CUDAGRAPHS""", """OFI""", """FX2TRT""", """ONNXRT""", """IPEX""", ] def _A (__a , __a=None , __a=None , __a=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = True while ask_again: SCREAMING_SNAKE_CASE_ : Any = input(UpperCamelCase__ ) try: if default is not None and len(UpperCamelCase__ ) == 0: return default return convert_value(UpperCamelCase__ ) if convert_value is not None else result except Exception: if error_message is not None: print(UpperCamelCase__ ) def _A (__a , __a=[] , __a=None , __a=0 ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = BulletMenu(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = menu.run(default_choice=UpperCamelCase__ ) return convert_value(UpperCamelCase__ ) if convert_value is not None else result def _A (__a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = int(UpperCamelCase__ ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = int(UpperCamelCase__ ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = int(UpperCamelCase__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _A (__a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = int(UpperCamelCase__ ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def _A (__a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = int(UpperCamelCase__ ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def _A (__a ) -> List[Any]: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = super()._format_usage(_a , _a , _a , _a) SCREAMING_SNAKE_CASE_ : List[Any] = usage.replace('''<command> [<args>] ''' , '''''') return usage
363
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
0
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ (lowercase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : int = {"""do_clean_text""": False, """add_prefix_space""": False} def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() # fmt: off UpperCAmelCase_ : Optional[int] = ["こん", "こんに", "にちは", "ばんは", "世界,㔺界", "、", "。", "<BR>", "<SP>", "<TAB>", "<URL>", "<EMAIL>", "<TEL>", "<DATE>", "<PRICE>", "<BLOCK>", "<KIGOU>", "<U2000U2BFF>", "<|emoji1|>", "<unk>", "<|bagoftoken|>", "<|endoftext|>"] # fmt: on UpperCAmelCase_ : List[Any] = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀 UpperCAmelCase_ : Dict = {"unk_token": "<unk>"} UpperCAmelCase_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["emoji_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.emoji_file , "w" ) as emoji_writer: emoji_writer.write(json.dumps(lowercase_ ) ) def UpperCamelCase__ ( self , **lowercase_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Any = "こんにちは、世界。 \nこんばんは、㔺界。😀" UpperCAmelCase_ : Union[str, Any] = "こんにちは、世界。 \nこんばんは、世界。😀" return input_text, output_text def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Tuple = self.get_input_output_texts(lowercase_ ) UpperCAmelCase_ : Optional[int] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) UpperCAmelCase_ : Optional[int] = tokenizer.decode(lowercase_ , clean_up_tokenization_spaces=lowercase_ ) return text, ids def UpperCamelCase__ ( self ): """simple docstring""" pass # TODO add if relevant def UpperCamelCase__ ( self ): """simple docstring""" pass # TODO add if relevant def UpperCamelCase__ ( self ): """simple docstring""" pass # TODO add if relevant def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = self.get_tokenizer() # Testing tokenization UpperCAmelCase_ : Tuple = "こんにちは、世界。 こんばんは、㔺界。" UpperCAmelCase_ : Dict = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"] UpperCAmelCase_ : int = tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) # Testing conversion to ids without special tokens UpperCAmelCase_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] UpperCAmelCase_ : Optional[Any] = tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) # Testing conversion to ids with special tokens UpperCAmelCase_ : Tuple = tokens + [tokenizer.unk_token] UpperCAmelCase_ : Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] UpperCAmelCase_ : int = tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.get_tokenizer() # Testing tokenization UpperCAmelCase_ : Optional[int] = "こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。" UpperCAmelCase_ : Optional[int] = "こんにちは、、、、世界。こんばんは、、、、世界。" UpperCAmelCase_ : Union[str, Any] = tokenizer.encode(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.decode(lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization UpperCAmelCase_ : List[Any] = "こんにちは、世界。" UpperCAmelCase_ : List[Any] = "こんばんは、㔺界。😀" UpperCAmelCase_ : List[Any] = "こんにちは、世界。こんばんは、世界。😀" UpperCAmelCase_ : Optional[Any] = tokenizer.encode(prefix_text + input_text ) UpperCAmelCase_ : List[str] = tokenizer.encode("" , prefix_text=prefix_text + input_text ) UpperCAmelCase_ : str = tokenizer.encode(lowercase_ , prefix_text=lowercase_ ) UpperCAmelCase_ : List[Any] = tokenizer.decode(lowercase_ ) UpperCAmelCase_ : str = tokenizer.decode(lowercase_ ) UpperCAmelCase_ : List[str] = tokenizer.decode(lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Dict = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization UpperCAmelCase_ : Union[str, Any] = "こんにちは、世界。" UpperCAmelCase_ : Union[str, Any] = "こんばんは、㔺界。😀" UpperCAmelCase_ : List[Any] = len(tokenizer.encode(lowercase_ ) ) - 2 UpperCAmelCase_ : Dict = len(tokenizer.encode(lowercase_ ) ) - 2 UpperCAmelCase_ : Union[str, Any] = [1] + [0] * (len_prefix + len_text + 1) UpperCAmelCase_ : Any = [1] * (len_prefix + len_text + 1) + [0] UpperCAmelCase_ : List[Any] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) UpperCAmelCase_ : Dict = tokenizer(prefix_text + input_text ).token_type_ids UpperCAmelCase_ : Optional[Any] = tokenizer("" , prefix_text=prefix_text + input_text ).token_type_ids UpperCAmelCase_ : str = tokenizer(lowercase_ , prefix_text=lowercase_ ).token_type_ids self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) UpperCAmelCase_ : str = tokenizer.encode("あンいワ" ) UpperCAmelCase_ : List[Any] = tokenizer.encode("" , prefix_text="あンいワ" ) UpperCAmelCase_ : str = tokenizer.encode("いワ" , prefix_text="あン" ) self.assertEqual(tokenizer.decode(lowercase_ ) , tokenizer.decode(lowercase_ ) ) self.assertEqual(tokenizer.decode(lowercase_ ) , tokenizer.decode(lowercase_ ) ) self.assertNotEqual(lowercase_ , lowercase_ ) self.assertNotEqual(lowercase_ , lowercase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) UpperCAmelCase_ : Tuple = [["武田信玄", "は、"], ["織田信長", "の配下の、"]] UpperCAmelCase_ : Dict = tokenizer(lowercase_ , padding=lowercase_ ) UpperCAmelCase_ : int = tokenizer.batch_encode_plus(lowercase_ , padding=lowercase_ ) # fmt: off UpperCAmelCase_ : str = [[3_5993, 8640, 2_5948, 3_5998, 3_0647, 3_5675, 3_5999, 3_5999], [3_5993, 1_0382, 9868, 3_5998, 3_0646, 9459, 3_0646, 3_5675]] UpperCAmelCase_ : Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] UpperCAmelCase_ : int = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , lowercase_ ) self.assertListEqual(x_token.token_type_ids , lowercase_ ) self.assertListEqual(x_token.attention_mask , lowercase_ ) self.assertListEqual(x_token_a.input_ids , lowercase_ ) self.assertListEqual(x_token_a.token_type_ids , lowercase_ ) self.assertListEqual(x_token_a.attention_mask , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def UpperCamelCase__ ( self ): """simple docstring""" # tokenizer has no padding token pass
61
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' while a != 0: __snake_case , __snake_case : Optional[Any] = b % a, a return b def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' if gcd(UpperCAmelCase_ , UpperCAmelCase_ ) != 1: __snake_case : Optional[Any] = F"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(UpperCAmelCase_ ) __snake_case , __snake_case , __snake_case : Optional[int] = 1, 0, a __snake_case , __snake_case , __snake_case : int = 0, 1, m while va != 0: __snake_case : Union[str, Any] = ua // va __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
172
0
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Dict = torch.nn.Linear(1_0 , 1_0 ) UpperCamelCase_: Optional[Any] = torch.optim.SGD(model.parameters() , 0.1 ) UpperCamelCase_: Tuple = Accelerator() UpperCamelCase_: Dict = accelerator.prepare(_A ) try: pickle.loads(pickle.dumps(_A ) ) except Exception as e: self.fail(f'''Accelerated optimizer pickling failed with {e}''' ) AcceleratorState._reset_state()
350
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def snake_case (UpperCAmelCase__ ) -> tuple: return (data["data"], data["target"]) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> np.ndarray: UpperCamelCase_: Dict = XGBRegressor(verbosity=0 , random_state=4_2 ) xgb.fit(UpperCAmelCase__ , UpperCAmelCase__ ) # Predict target for test data UpperCamelCase_: int = xgb.predict(UpperCAmelCase__ ) UpperCamelCase_: Any = predictions.reshape(len(UpperCAmelCase__ ) , 1 ) return predictions def snake_case () -> None: UpperCamelCase_: Union[str, Any] = fetch_california_housing() UpperCamelCase_ ,UpperCamelCase_: Tuple = data_handling(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Optional[Any] = train_test_split( UpperCAmelCase__ , UpperCAmelCase__ , test_size=0.25 , random_state=1 ) UpperCamelCase_: Union[str, Any] = xgboost(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Error printing print(F'''Mean Absolute Error : {mean_absolute_error(UpperCAmelCase__ , UpperCAmelCase__ )}''' ) print(F'''Mean Square Error : {mean_squared_error(UpperCAmelCase__ , UpperCAmelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
292
0
"""simple docstring""" import sys import turtle def A__ ( UpperCamelCase , UpperCamelCase ): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(_snake_case , get_mid(_snake_case , _snake_case ) , get_mid(_snake_case , _snake_case ) , depth - 1 ) triangle(_snake_case , get_mid(_snake_case , _snake_case ) , get_mid(_snake_case , _snake_case ) , depth - 1 ) triangle(_snake_case , get_mid(_snake_case , _snake_case ) , get_mid(_snake_case , _snake_case ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) _snake_case : List[Any] = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') _snake_case : Union[str, Any] = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
292
"""simple docstring""" import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib UpperCAmelCase__ : Optional[int] = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } UpperCAmelCase__ : List[Any] = logging.WARNING def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.getenv("""DATASETS_VERBOSITY""" ,_snake_case ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'''Unknown option DATASETS_VERBOSITY={env_level_str}, ''' f'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def lowercase_ ( ): return __name__.split(""".""" )[0] def lowercase_ ( ): return logging.getLogger(_get_library_name() ) def lowercase_ ( ): # Apply our default configuration to the library root logger. SCREAMING_SNAKE_CASE__ : Optional[Any] = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Optional[Any] = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def lowercase_ ( _snake_case = None ): if name is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = _get_library_name() return logging.getLogger(_snake_case ) def lowercase_ ( ): return _get_library_root_logger().getEffectiveLevel() def lowercase_ ( _snake_case ): _get_library_root_logger().setLevel(_snake_case ) def lowercase_ ( ): return set_verbosity(_snake_case ) def lowercase_ ( ): return set_verbosity(_snake_case ) def lowercase_ ( ): return set_verbosity(_snake_case ) def lowercase_ ( ): return set_verbosity(_snake_case ) def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Tuple = False def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : str = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class lowerCAmelCase_ : """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> int: # pylint: disable=unused-argument """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = args[0] if args else None def __iter__(self ) -> int: """simple docstring""" return iter(self._iterator ) def __getattr__(self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" def empty_fn(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): # pylint: disable=unused-argument return return empty_fn def __enter__(self ) -> Dict: """simple docstring""" return self def __exit__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" return UpperCAmelCase__ : str = True class lowerCAmelCase_ : """simple docstring""" def __call__(self , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" if _tqdm_active and not disable: return tqdm_lib.tqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: return EmptyTqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Optional[Any]: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() UpperCAmelCase__ : Tuple = _tqdm_cls() def lowercase_ ( ): global _tqdm_active return bool(_tqdm_active ) def lowercase_ ( ): global _tqdm_active SCREAMING_SNAKE_CASE__ : Union[str, Any] = True def lowercase_ ( ): global _tqdm_active SCREAMING_SNAKE_CASE__ : str = False
25
0
"""simple docstring""" from torch import nn def __snake_case ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'Unsupported activation function: {act_fn}' )
202
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : Union[str, Any] = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Any = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Any = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : List[str] = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _lowerCAmelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
202
1
def lowercase_ (A : list[int] ): snake_case__ : int = len(A ) for i in range(A ): for j in range(i + 1 , A ): if numbers[j] < numbers[i]: snake_case__ , snake_case__ : Dict = numbers[j], numbers[i] return numbers if __name__ == "__main__": a_ :List[Any] = input("Enter numbers separated by a comma:\n").strip() a_ :Union[str, Any] = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
277
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo a_ :Any = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" a_ :List[str] = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" a_ :List[str] = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): """simple docstring""" def lowercase_ ( self : str ) ->MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string', id='token' ), id='sequence' ), id='references' ), } ), ) def lowercase_ ( self : str, _snake_case : List[List[List[str]]], _snake_case : List[List[str]], _snake_case : int = 1, _snake_case : int = 4, ) ->Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_snake_case, hypotheses=_snake_case, min_len=_snake_case, max_len=_snake_case ) }
277
1
"""simple docstring""" def lowerCamelCase_ (UpperCamelCase__ : int = 1 , UpperCamelCase__ : int = 1000 ): _UpperCAmelCase : List[str] = 1 _UpperCAmelCase : Any = 0 for divide_by_number in range(UpperCamelCase__ , digit + 1 ): _UpperCAmelCase : list[int] = [] _UpperCAmelCase : int = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(UpperCamelCase__ ): _UpperCAmelCase : Optional[Any] = len(UpperCamelCase__ ) _UpperCAmelCase : int = divide_by_number else: has_been_divided.append(UpperCamelCase__ ) _UpperCAmelCase : Tuple = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
68
"""simple docstring""" import datasets from .evaluate import evaluate _lowerCAmelCase :int = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' _lowerCAmelCase :int = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' _lowerCAmelCase :str = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\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\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\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 CUAD 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\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def __lowerCAmelCase ( self ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , A , A ) -> List[Any]: _UpperCAmelCase : Optional[int] = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} _UpperCAmelCase : Optional[Any] = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] _UpperCAmelCase : Union[str, Any] = evaluate(dataset=A , predictions=A ) return score
68
1
'''simple docstring''' def lowercase__ ( __UpperCamelCase = 1000 )-> int: UpperCamelCase = 2**power UpperCamelCase = str(__UpperCamelCase ) UpperCamelCase = list(__UpperCamelCase ) UpperCamelCase = 0 for i in list_num: sum_of_num += int(__UpperCamelCase ) return sum_of_num if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = int(input('Enter the power of 2: ').strip()) print('2 ^ ', power, ' = ', 2**power) SCREAMING_SNAKE_CASE__ = solution(power) print('Sum of the digits is: ', result)
321
'''simple docstring''' import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE__ = importlib.util.find_spec('s3fs') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE__ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def lowercase__ ( __UpperCamelCase )-> str: if "://" in dataset_path: UpperCamelCase = dataset_path.split("""://""" )[1] return dataset_path def lowercase__ ( __UpperCamelCase )-> bool: if fs is not None and fs.protocol != "file": return True else: return False def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> int: UpperCamelCase = not is_remote_filesystem(__UpperCamelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(__UpperCamelCase ) , fs._strip_protocol(__UpperCamelCase ) ) else: fs.mv(__UpperCamelCase , __UpperCamelCase , recursive=__UpperCamelCase ) def lowercase__ ( )-> None: if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: UpperCamelCase = None UpperCamelCase = None UpperCamelCase = threading.Lock()
321
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCAmelCase_ ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): __lowerCAmelCase = 3_84 if "tiny" in model_name: __lowerCAmelCase = [3, 3, 9, 3] __lowerCAmelCase = [96, 1_92, 3_84, 7_68] if "small" in model_name: __lowerCAmelCase = [3, 3, 27, 3] __lowerCAmelCase = [96, 1_92, 3_84, 7_68] if "base" in model_name: __lowerCAmelCase = [3, 3, 27, 3] __lowerCAmelCase = [1_28, 2_56, 5_12, 10_24] __lowerCAmelCase = 5_12 if "large" in model_name: __lowerCAmelCase = [3, 3, 27, 3] __lowerCAmelCase = [1_92, 3_84, 7_68, 15_36] __lowerCAmelCase = 7_68 if "xlarge" in model_name: __lowerCAmelCase = [3, 3, 27, 3] __lowerCAmelCase = [2_56, 5_12, 10_24, 20_48] __lowerCAmelCase = 10_24 # set label information __lowerCAmelCase = 1_50 __lowerCAmelCase = '''huggingface/label-files''' __lowerCAmelCase = '''ade20k-id2label.json''' __lowerCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type="dataset" ) , "r" ) ) __lowerCAmelCase = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} __lowerCAmelCase = {v: k for k, v in idalabel.items()} __lowerCAmelCase = ConvNextConfig( depths=SCREAMING_SNAKE_CASE__ , hidden_sizes=SCREAMING_SNAKE_CASE__ , out_features=["stage1", "stage2", "stage3", "stage4"] ) __lowerCAmelCase = UperNetConfig( backbone_config=SCREAMING_SNAKE_CASE__ , auxiliary_in_channels=SCREAMING_SNAKE_CASE__ , num_labels=SCREAMING_SNAKE_CASE__ , idalabel=SCREAMING_SNAKE_CASE__ , labelaid=SCREAMING_SNAKE_CASE__ , ) return config def UpperCAmelCase_ ( SCREAMING_SNAKE_CASE_ : List[Any] ): __lowerCAmelCase = [] # fmt: off # stem rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight") ) rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias") ) rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight") ) rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"""backbone.stages.{i}.{j}.gamma""", F"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((F"""backbone.downsample_layers.{i}.0.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.0.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") ) rename_keys.append((F"""backbone.norm{i}.weight""", F"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((F"""backbone.norm{i}.bias""", F"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"), ("decode_head.conv_seg.bias", "decode_head.classifier.bias"), ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"), ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"), ] ) # fmt: on return rename_keys def UpperCAmelCase_ ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ): __lowerCAmelCase = dct.pop(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = val def UpperCAmelCase_ ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } __lowerCAmelCase = model_name_to_url[model_name] __lowerCAmelCase = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location="cpu" )['''state_dict'''] __lowerCAmelCase = get_upernet_config(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = UperNetForSemanticSegmentation(SCREAMING_SNAKE_CASE__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "bn" in key: __lowerCAmelCase = key.replace("bn" , "batch_norm" ) __lowerCAmelCase = val # rename keys __lowerCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify on image __lowerCAmelCase = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' __lowerCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert("RGB" ) __lowerCAmelCase = SegformerImageProcessor() __lowerCAmelCase = processor(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).pixel_values with torch.no_grad(): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ ) if model_name == "upernet-convnext-tiny": __lowerCAmelCase = torch.tensor( [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]] ) elif model_name == "upernet-convnext-small": __lowerCAmelCase = torch.tensor( [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]] ) elif model_name == "upernet-convnext-base": __lowerCAmelCase = torch.tensor( [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]] ) elif model_name == "upernet-convnext-large": __lowerCAmelCase = torch.tensor( [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]] ) elif model_name == "upernet-convnext-xlarge": __lowerCAmelCase = torch.tensor( [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]] ) print("Logits:" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) 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(SCREAMING_SNAKE_CASE__ ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print(F"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(F"""openmmlab/{model_name}""" ) processor.push_to_hub(F"""openmmlab/{model_name}""" ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[f'''upernet-convnext-{size}''' for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet 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.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCamelCase__ = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
367
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def _a ( SCREAMING_SNAKE_CASE_ : Any ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict ): __lowerCAmelCase = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __lowerCAmelCase = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __lowerCAmelCase = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __lowerCAmelCase = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __lowerCAmelCase = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __lowerCAmelCase = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __lowerCAmelCase = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __lowerCAmelCase = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __lowerCAmelCase = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __lowerCAmelCase = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __lowerCAmelCase = key.replace("image_encoder.module" , "flava.image_model" ) __lowerCAmelCase = key.replace("text_encoder.module" , "flava.text_model" ) __lowerCAmelCase = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __lowerCAmelCase = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __lowerCAmelCase = key.replace("text_projection" , "flava.text_projection" ) __lowerCAmelCase = key.replace("image_projection" , "flava.image_projection" ) __lowerCAmelCase = value.float() for key, value in codebook_state_dict.items(): __lowerCAmelCase = value return upgrade @torch.no_grad() def _a ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int=None ): if config_path is not None: __lowerCAmelCase = FlavaConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) else: __lowerCAmelCase = FlavaConfig() __lowerCAmelCase = FlavaForPreTraining(SCREAMING_SNAKE_CASE_ ).eval() __lowerCAmelCase = convert_dalle_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , save_checkpoint=SCREAMING_SNAKE_CASE_ ) if os.path.exists(SCREAMING_SNAKE_CASE_ ): __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) else: __lowerCAmelCase = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) __lowerCAmelCase = upgrade_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) hf_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = hf_model.state_dict() __lowerCAmelCase = count_parameters(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = count_parameters(SCREAMING_SNAKE_CASE_ ) + count_parameters(SCREAMING_SNAKE_CASE_ ) assert torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") UpperCamelCase__ = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
102
0
"""simple docstring""" import copy import re class lowercase__ : _UpperCAmelCase :Any = "hp" _UpperCAmelCase :Any = {} _UpperCAmelCase :Dict = None @classmethod def UpperCAmelCase__ ( cls : str , snake_case__ : str , snake_case__ : str ): lowerCamelCase_ : str =prefix lowerCamelCase_ : int =defaults cls.build_naming_info() @staticmethod def UpperCAmelCase__ ( snake_case__ : Any , snake_case__ : Optional[int] ): if len(snake_case__ ) == 0: return "" lowerCamelCase_ : List[Any] =None if any(char.isdigit() for char in word ): raise Exception(F"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(snake_case__ ) + 1 ): lowerCamelCase_ : List[str] =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: lowerCamelCase_ : str =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(snake_case__ : List[Any] ): lowerCamelCase_ : int ='''''' while integer != 0: lowerCamelCase_ : Optional[int] =chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s lowerCamelCase_ : int =0 while True: lowerCamelCase_ : int =word + '''#''' + int_to_alphabetic(snake_case__ ) if sword in info["reverse_short_word"]: continue else: lowerCamelCase_ : Any =sword break lowerCamelCase_ : str =short_word lowerCamelCase_ : Union[str, Any] =word return short_word @staticmethod def UpperCAmelCase__ ( snake_case__ : int , snake_case__ : Optional[Any] ): lowerCamelCase_ : Any =param_name.split("_" ) lowerCamelCase_ : Optional[Any] =[TrialShortNamer.shortname_for_word(snake_case__ , snake_case__ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name lowerCamelCase_ : Dict =['''''', '''_'''] for separator in separators: lowerCamelCase_ : Optional[int] =separator.join(snake_case__ ) if shortname not in info["reverse_short_param"]: lowerCamelCase_ : str =shortname lowerCamelCase_ : List[str] =param_name return shortname return param_name @staticmethod def UpperCAmelCase__ ( snake_case__ : List[Any] , snake_case__ : Optional[int] ): lowerCamelCase_ : Union[str, Any] =TrialShortNamer.shortname_for_key(snake_case__ , snake_case__ ) lowerCamelCase_ : str =short_name lowerCamelCase_ : List[Any] =param_name @classmethod def UpperCAmelCase__ ( cls : Dict ): if cls.NAMING_INFO is not None: return lowerCamelCase_ : Union[str, Any] ={ '''short_word''': {}, '''reverse_short_word''': {}, '''short_param''': {}, '''reverse_short_param''': {}, } lowerCamelCase_ : List[str] =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(snake_case__ , snake_case__ ) lowerCamelCase_ : str =info @classmethod def UpperCAmelCase__ ( cls : Tuple , snake_case__ : List[Any] ): cls.build_naming_info() assert cls.PREFIX is not None lowerCamelCase_ : str =[copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue lowerCamelCase_ : List[str] =cls.NAMING_INFO['''short_param'''][k] if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ : Any =1 if v else 0 lowerCamelCase_ : Any ='''''' if isinstance(snake_case__ , (int, float) ) else '''-''' lowerCamelCase_ : Optional[Any] =F"""{key}{sep}{v}""" name.append(snake_case__ ) return "_".join(snake_case__ ) @classmethod def UpperCAmelCase__ ( cls : Dict , snake_case__ : Dict ): lowerCamelCase_ : Union[str, Any] =repr[len(cls.PREFIX ) + 1 :] if repr == "": lowerCamelCase_ : Optional[int] =[] else: lowerCamelCase_ : List[str] =repr.split("_" ) lowerCamelCase_ : int ={} for value in values: if "-" in value: lowerCamelCase_ : int =value.split("-" ) else: lowerCamelCase_ : Union[str, Any] =re.sub("[0-9.]" , "" , snake_case__ ) lowerCamelCase_ : Dict =float(re.sub("[^0-9.]" , "" , snake_case__ ) ) lowerCamelCase_ : str =cls.NAMING_INFO['''reverse_short_param'''][p_k] lowerCamelCase_ : List[str] =p_v for k in cls.DEFAULTS: if k not in parameters: lowerCamelCase_ : Union[str, Any] =cls.DEFAULTS[k] return parameters
144
'''simple docstring''' snake_case_ : List[str] = { "Pillow": "Pillow<10.0.0", "accelerate": "accelerate>=0.20.3", "av": "av==9.2.0", "beautifulsoup4": "beautifulsoup4", "black": "black~=23.1", "codecarbon": "codecarbon==1.2.0", "cookiecutter": "cookiecutter==1.7.3", "dataclasses": "dataclasses", "datasets": "datasets!=2.5.0", "decord": "decord==0.6.0", "deepspeed": "deepspeed>=0.9.3", "diffusers": "diffusers", "dill": "dill<0.3.5", "evaluate": "evaluate>=0.2.0", "fairscale": "fairscale>0.3", "faiss-cpu": "faiss-cpu", "fastapi": "fastapi", "filelock": "filelock", "flax": "flax>=0.4.1,<=0.7.0", "ftfy": "ftfy", "fugashi": "fugashi>=1.0", "GitPython": "GitPython<3.1.19", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.14.1,<1.0", "importlib_metadata": "importlib_metadata", "ipadic": "ipadic>=1.0.0,<2.0", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2,<=0.4.13", "jaxlib": "jaxlib>=0.1.65,<=0.4.13", "jieba": "jieba", "kenlm": "kenlm", "keras-nlp": "keras-nlp>=0.3.1", "librosa": "librosa", "nltk": "nltk", "natten": "natten>=0.14.6", "numpy": "numpy>=1.17", "onnxconverter-common": "onnxconverter-common", "onnxruntime-tools": "onnxruntime-tools>=1.4.2", "onnxruntime": "onnxruntime>=1.4.0", "opencv-python": "opencv-python", "optuna": "optuna", "optax": "optax>=0.0.8,<=0.1.4", "packaging": "packaging>=20.0", "parameterized": "parameterized", "phonemizer": "phonemizer", "protobuf": "protobuf", "psutil": "psutil", "pyyaml": "pyyaml>=5.1", "pydantic": "pydantic<2", "pytest": "pytest>=7.2.0", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "python": "python>=3.8.0", "ray[tune]": "ray[tune]", "regex": "regex!=2019.12.17", "requests": "requests", "rhoknp": "rhoknp>=1.1.0,<1.3.1", "rjieba": "rjieba", "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff": "ruff>=0.0.241,<=0.0.259", "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", "sacremoses": "sacremoses", "safetensors": "safetensors>=0.3.1", "sagemaker": "sagemaker>=2.31.0", "scikit-learn": "scikit-learn", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "sigopt": "sigopt", "starlette": "starlette", "sudachipy": "sudachipy>=0.6.6", "sudachidict_core": "sudachidict_core>=20220729", "tensorflow-cpu": "tensorflow-cpu>=2.6,<2.14", "tensorflow": "tensorflow>=2.6,<2.14", "tensorflow-text": "tensorflow-text<2.14", "tf2onnx": "tf2onnx", "timeout-decorator": "timeout-decorator", "timm": "timm", "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14", "torch": "torch>=1.9,!=1.12.0", "torchaudio": "torchaudio", "torchvision": "torchvision", "pyctcdecode": "pyctcdecode>=0.4.0", "tqdm": "tqdm>=4.27", "unidic": "unidic>=1.0.2", "unidic_lite": "unidic_lite>=1.0.7", "urllib3": "urllib3<2.0.0", "uvicorn": "uvicorn", }
125
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _a : '''simple docstring''' def __init__( self, A, A=13, A=7, A=True, A=True, A=True, A=99, A=32, A=5, A=4, A=37, A="gelu", A=0.1, A=0.1, A=512, A=16, A=2, A=0.02, A=3, A=4, A=None, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Tuple = batch_size SCREAMING_SNAKE_CASE : Dict = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : List[str] = use_token_type_ids SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : List[str] = vocab_size SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : Any = num_labels SCREAMING_SNAKE_CASE : str = num_choices SCREAMING_SNAKE_CASE : List[Any] = scope SCREAMING_SNAKE_CASE : List[Any] = self.vocab_size - 1 def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size], self.num_choices ) SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTConfig( vocab_size=self.vocab_size, n_embd=self.hidden_size, n_layer=self.num_hidden_layers, n_head=self.num_attention_heads, n_positions=self.max_position_embeddings, pad_token_id=self.pad_token_id, ) SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def UpperCamelCase_ ( self, A, A, A, A, *A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = OpenAIGPTModel(config=A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(A, token_type_ids=A, head_mask=A ) SCREAMING_SNAKE_CASE : str = model(A, token_type_ids=A ) SCREAMING_SNAKE_CASE : Any = model(A ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self, A, A, A, A, *A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = OpenAIGPTLMHeadModel(A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(A, token_type_ids=A, labels=A ) self.parent.assertEqual(result.loss.shape, () ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self, A, A, A, A, *A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = OpenAIGPTDoubleHeadsModel(A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(A, token_type_ids=A, labels=A ) self.parent.assertEqual(result.loss.shape, () ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self, A, A, A, A, *A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.num_labels SCREAMING_SNAKE_CASE : Tuple = OpenAIGPTForSequenceClassification(A ) model.to(A ) model.eval() SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[int] = model(A, token_type_ids=A, labels=A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : int = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : List[str] = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) A : Any = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly A : int = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def UpperCamelCase_ ( self, A, A, A, A, A ): '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def UpperCamelCase_ ( self, A, A, A=False ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = super()._prepare_for_class(A, A, return_labels=A ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length), dtype=torch.long, device=A, ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict['labels'] SCREAMING_SNAKE_CASE : str = inputs_dict['labels'] SCREAMING_SNAKE_CASE : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices), dtype=torch.long, device=A, ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=A ) return inputs_dict def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = OpenAIGPTModelTester(self ) SCREAMING_SNAKE_CASE : Tuple = ConfigTester(self, config_class=A, n_embd=37 ) def UpperCamelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*A ) @slow def UpperCamelCase_ ( self ): '''simple docstring''' for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : str = OpenAIGPTModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_torch class _a ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(A ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[481, 4_735, 544]], dtype=torch.long, device=A ) # the president is SCREAMING_SNAKE_CASE : Tuple = [ 481, 4_735, 544, 246, 963, 870, 762, 239, 244, 40_477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the SCREAMING_SNAKE_CASE : Optional[Any] = model.generate(A, do_sample=A ) self.assertListEqual(output_ids[0].tolist(), A )
246
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase_ = {"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
246
1
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def UpperCAmelCase_ ( __lowercase : List[str] ) -> List[str]: '''simple docstring''' monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def UpperCAmelCase_ ( __lowercase : Optional[Any] ) -> Any: '''simple docstring''' class A_ : def __init__( self : Optional[int] , snake_case_ : str ): _UpperCAmelCase = metric_id class A_ : _lowerCamelCase : Any = [MetricMock(lowerCAmelCase_ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def lowercase ( self : Tuple ): return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def UpperCAmelCase_ ( __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : List[str] ) -> int: '''simple docstring''' if "tmp_path" in args: _UpperCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(__lowercase , match="https://huggingface.co/docs/evaluate" ): func(*__lowercase )
22
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def UpperCamelCase ( __lowerCamelCase : Optional[int] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def UpperCamelCase ( __lowerCamelCase : str ): class UpperCAmelCase : def __init__(self : Optional[int] , snake_case__ : str ) -> Any: '''simple docstring''' snake_case : List[str] = metric_id class UpperCAmelCase : A__ : List[str] = [MetricMock(A_ ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def _SCREAMING_SNAKE_CASE (self : int ) -> List[str]: '''simple docstring''' return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : Any ): if "tmp_path" in args: snake_case : str = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(__lowerCamelCase , match="https://huggingface.co/docs/evaluate" ): func(*__lowerCamelCase )
59
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { '''microsoft/unispeech-large-1500h-cv''': ( '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json''' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class __SCREAMING_SNAKE_CASE ( A__ ): A : str = 'unispeech' def __init__( self , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__="group" , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE__=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE__=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.05 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=320 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=100 , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="mean" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=80 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.5 , **SCREAMING_SNAKE_CASE__ , ): super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) lowercase : Any = hidden_size lowercase : str = feat_extract_norm lowercase : Any = feat_extract_activation lowercase : int = list(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = list(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = list(SCREAMING_SNAKE_CASE__ ) lowercase : Dict = conv_bias lowercase : Tuple = num_conv_pos_embeddings lowercase : List[str] = num_conv_pos_embedding_groups lowercase : Union[str, Any] = len(self.conv_dim ) lowercase : Optional[int] = num_hidden_layers lowercase : Dict = intermediate_size lowercase : Optional[int] = hidden_act lowercase : Optional[Any] = num_attention_heads lowercase : Union[str, Any] = hidden_dropout lowercase : int = attention_dropout lowercase : Union[str, Any] = activation_dropout lowercase : str = feat_proj_dropout lowercase : Tuple = final_dropout lowercase : Dict = layerdrop lowercase : str = layer_norm_eps lowercase : Any = initializer_range lowercase : Tuple = num_ctc_classes lowercase : List[str] = vocab_size lowercase : Optional[Any] = do_stable_layer_norm lowercase : int = use_weighted_layer_sum lowercase : Any = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" f""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase : Optional[Any] = apply_spec_augment lowercase : List[str] = mask_time_prob lowercase : Tuple = mask_time_length lowercase : str = mask_time_min_masks lowercase : int = mask_feature_prob lowercase : Union[str, Any] = mask_feature_length lowercase : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations lowercase : List[Any] = num_codevectors_per_group lowercase : Dict = num_codevector_groups lowercase : str = contrastive_logits_temperature lowercase : Optional[Any] = feat_quantizer_dropout lowercase : Optional[Any] = num_negatives lowercase : Union[str, Any] = codevector_dim lowercase : List[str] = proj_codevector_dim lowercase : Optional[Any] = diversity_loss_weight # ctc loss lowercase : Optional[int] = ctc_loss_reduction lowercase : Any = ctc_zero_infinity # pretraining loss lowercase : List[Any] = replace_prob @property def __lowerCamelCase ( self ): return functools.reduce(operator.mul , self.conv_stride , 1 )
365
import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->Union[str, Any]: """simple docstring""" lowercase : Any = os.path.abspath(_UpperCamelCase ) logger.info(f"""Converting TensorFlow checkpoint from {tf_path}""" ) # Load weights from TF model lowercase : Optional[int] = tf.train.list_variables(_UpperCamelCase ) lowercase : Optional[int] = [] lowercase : Optional[int] = [] lowercase : Optional[Any] = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") lowercase : int = full_name.split('''/''' ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f"""Skipping non-model layer {full_name}""" ) continue if "optimizer" in full_name: logger.info(f"""Skipping optimization layer {full_name}""" ) continue if name[0] == "model": # ignore initial 'model' lowercase : List[Any] = name[1:] # figure out how many levels deep the name is lowercase : Optional[int] = 0 for _name in name: if _name.startswith('''layer_with_weights''' ): depth += 1 else: break layer_depth.append(_UpperCamelCase ) # read data lowercase : Any = tf.train.load_variable(_UpperCamelCase, _UpperCamelCase ) names.append('''/'''.join(_UpperCamelCase ) ) arrays.append(_UpperCamelCase ) logger.info(f"""Read a total of {len(_UpperCamelCase ):,} layers""" ) # Sanity check if len(set(_UpperCamelCase ) ) != 1: raise ValueError(f"""Found layer names with different depths (layer depth {list(set(_UpperCamelCase ) )})""" ) lowercase : List[str] = list(set(_UpperCamelCase ) )[0] if layer_depth != 1: raise ValueError( '''The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP''' ''' heads.''' ) # convert layers logger.info('''Converting weights...''' ) for full_name, array in zip(_UpperCamelCase, _UpperCamelCase ): lowercase : Optional[int] = full_name.split('''/''' ) lowercase : Tuple = model lowercase : Any = [] for i, m_name in enumerate(_UpperCamelCase ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith('''layer_with_weights''' ): lowercase : Tuple = int(m_name.split('''-''' )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(['''embeddings''', '''LayerNorm'''] ) lowercase : int = getattr(_UpperCamelCase, '''embeddings''' ) lowercase : Optional[Any] = getattr(_UpperCamelCase, '''LayerNorm''' ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(['''encoder''', '''layer''', str(layer_num - 4 )] ) lowercase : int = getattr(_UpperCamelCase, '''encoder''' ) lowercase : Tuple = getattr(_UpperCamelCase, '''layer''' ) lowercase : List[Any] = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(['''pooler''', '''dense'''] ) lowercase : str = getattr(_UpperCamelCase, '''pooler''' ) lowercase : str = getattr(_UpperCamelCase, '''dense''' ) elif m_name == "embeddings": trace.append('''embeddings''' ) lowercase : Optional[int] = getattr(_UpperCamelCase, '''embeddings''' ) if layer_num == 0: trace.append('''word_embeddings''' ) lowercase : str = getattr(_UpperCamelCase, '''word_embeddings''' ) elif layer_num == 1: trace.append('''position_embeddings''' ) lowercase : List[Any] = getattr(_UpperCamelCase, '''position_embeddings''' ) elif layer_num == 2: trace.append('''token_type_embeddings''' ) lowercase : int = getattr(_UpperCamelCase, '''token_type_embeddings''' ) else: raise ValueError(f"""Unknown embedding layer with name {full_name}""" ) trace.append('''weight''' ) lowercase : Union[str, Any] = getattr(_UpperCamelCase, '''weight''' ) elif m_name == "_attention_layer": # self-attention layer trace.extend(['''attention''', '''self'''] ) lowercase : Tuple = getattr(_UpperCamelCase, '''attention''' ) lowercase : str = getattr(_UpperCamelCase, '''self''' ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(['''attention''', '''output''', '''LayerNorm'''] ) lowercase : Dict = getattr(_UpperCamelCase, '''attention''' ) lowercase : Any = getattr(_UpperCamelCase, '''output''' ) lowercase : Union[str, Any] = getattr(_UpperCamelCase, '''LayerNorm''' ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(['''attention''', '''output''', '''dense'''] ) lowercase : Union[str, Any] = getattr(_UpperCamelCase, '''attention''' ) lowercase : str = getattr(_UpperCamelCase, '''output''' ) lowercase : Optional[int] = getattr(_UpperCamelCase, '''dense''' ) elif m_name == "_output_dense": # output dense trace.extend(['''output''', '''dense'''] ) lowercase : List[str] = getattr(_UpperCamelCase, '''output''' ) lowercase : str = getattr(_UpperCamelCase, '''dense''' ) elif m_name == "_output_layer_norm": # output dense trace.extend(['''output''', '''LayerNorm'''] ) lowercase : Dict = getattr(_UpperCamelCase, '''output''' ) lowercase : int = getattr(_UpperCamelCase, '''LayerNorm''' ) elif m_name == "_key_dense": # attention key trace.append('''key''' ) lowercase : Optional[Any] = getattr(_UpperCamelCase, '''key''' ) elif m_name == "_query_dense": # attention query trace.append('''query''' ) lowercase : Dict = getattr(_UpperCamelCase, '''query''' ) elif m_name == "_value_dense": # attention value trace.append('''value''' ) lowercase : Optional[Any] = getattr(_UpperCamelCase, '''value''' ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(['''intermediate''', '''dense'''] ) lowercase : List[str] = getattr(_UpperCamelCase, '''intermediate''' ) lowercase : Optional[int] = getattr(_UpperCamelCase, '''dense''' ) elif m_name == "_output_layer_norm": # output layer norm trace.append('''output''' ) lowercase : Tuple = getattr(_UpperCamelCase, '''output''' ) # weights & biases elif m_name in ["bias", "beta"]: trace.append('''bias''' ) lowercase : str = getattr(_UpperCamelCase, '''bias''' ) elif m_name in ["kernel", "gamma"]: trace.append('''weight''' ) lowercase : Dict = getattr(_UpperCamelCase, '''weight''' ) else: logger.warning(f"""Ignored {m_name}""" ) # for certain layers reshape is necessary lowercase : Any = '''.'''.join(_UpperCamelCase ) if re.match(R'''(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)''', _UpperCamelCase ) or re.match( R'''(\S+)\.attention\.output\.dense\.weight''', _UpperCamelCase ): lowercase : Any = array.reshape(pointer.data.shape ) if "kernel" in full_name: lowercase : List[str] = array.transpose() if pointer.shape == array.shape: lowercase : Optional[Any] = torch.from_numpy(_UpperCamelCase ) else: raise ValueError( f"""Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:""" f""" {array.shape}""" ) logger.info(f"""Successfully set variable {full_name} to PyTorch layer {trace}""" ) return model def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->Tuple: """simple docstring""" logger.info(f"""Loading model based on config from {config_path}...""" ) lowercase : List[Any] = BertConfig.from_json_file(_UpperCamelCase ) lowercase : Dict = BertModel(_UpperCamelCase ) # Load weights from checkpoint logger.info(f"""Loading weights from checkpoint {tf_checkpoint_path}...""" ) load_tfa_weights_in_bert(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) # Save pytorch-model logger.info(f"""Saving PyTorch model to {pytorch_dump_path}...""" ) torch.save(model.state_dict(), _UpperCamelCase ) if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument( '''--tf_checkpoint_path''', type=str, required=True, help='''Path to the TensorFlow 2.x checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', type=str, required=True, help='''The config json file corresponding to the BERT model. This specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', type=str, required=True, help='''Path to the output PyTorch model (must include filename).''', ) __a = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
173
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class _lowerCamelCase : """simple docstring""" snake_case = 42 snake_case = field(default_factory=UpperCamelCase ) snake_case = field(default_factory=UpperCamelCase ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->Optional[int]: '''simple docstring''' A_ : Any = len(list(m.modules() ) ) == 1 or isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ) or isinstance(_SCREAMING_SNAKE_CASE , nn.BatchNormad ) if has_not_submodules: self.traced.append(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE )->int: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_SCREAMING_SNAKE_CASE ) [x.remove() for x in self.handles] return self @property def _snake_case ( self )->Dict: '''simple docstring''' return list(filter(lambda _SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _lowerCamelCase : """simple docstring""" snake_case = 42 snake_case = 42 snake_case = 1 snake_case = field(default_factory=UpperCamelCase ) snake_case = field(default_factory=UpperCamelCase ) snake_case = True def __call__( self , _SCREAMING_SNAKE_CASE )->List[Any]: '''simple docstring''' A_ : str = Tracker(self.dest )(_SCREAMING_SNAKE_CASE ).parametrized A_ : Tuple = Tracker(self.src )(_SCREAMING_SNAKE_CASE ).parametrized A_ : Any = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.src_skip , _SCREAMING_SNAKE_CASE ) ) A_ : List[Any] = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.dest_skip , _SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(_SCREAMING_SNAKE_CASE )} operations while''' F''' destination module has {len(_SCREAMING_SNAKE_CASE )}.''' ) for dest_m, src_m in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class _lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , _SCREAMING_SNAKE_CASE )->str: '''simple docstring''' super().__init__() A_ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('''conv1''', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('''block''' ), F'''Unexpected layer name {k}''' A_ : Tuple = len(_SCREAMING_SNAKE_CASE ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) A_ : str = nn.ModuleDict(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )->Any: '''simple docstring''' return get_trunk_forward_outputs( _SCREAMING_SNAKE_CASE , out_feat_keys=_SCREAMING_SNAKE_CASE , feature_blocks=self._feature_blocks , ) class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" def _snake_case ( self , _SCREAMING_SNAKE_CASE )->str: '''simple docstring''' A_ : List[Any] = x.split('''-''' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self , _SCREAMING_SNAKE_CASE )->Callable[[], Tuple[nn.Module, Dict]]: '''simple docstring''' if x not in self: A_ : List[str] = self.convert_name_to_timm(_SCREAMING_SNAKE_CASE ) A_ : Any = partial(lambda: (timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ).eval(), None) ) else: A_ : List[Any] = super().__getitem__(_SCREAMING_SNAKE_CASE ) return val class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" def __getitem__( self , _SCREAMING_SNAKE_CASE )->Callable[[], nn.Module]: '''simple docstring''' if "seer" in x and "in1k" not in x: A_ : Dict = RegNetModel else: A_ : Any = RegNetForImageClassification return val def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): for from_key, to_key in keys: A_ : List[Any] = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = True , ): print(f'''Converting {name}...''' ) with torch.no_grad(): A_ , A_ : List[str] = from_model_func() A_ : int = our_model_func(SCREAMING_SNAKE_CASE ).eval() A_ : str = ModuleTransfer(src=SCREAMING_SNAKE_CASE , dest=SCREAMING_SNAKE_CASE , raise_if_mismatch=SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = torch.randn((1, 3, 224, 224) ) module_transfer(SCREAMING_SNAKE_CASE ) if from_state_dict is not None: A_ : str = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: A_ : List[Any] = [('''0.clf.0.weight''', '''classifier.1.weight'''), ('''0.clf.0.bias''', '''classifier.1.bias''')] A_ : Union[str, Any] = manually_copy_vissl_head(SCREAMING_SNAKE_CASE , our_model.state_dict() , SCREAMING_SNAKE_CASE ) our_model.load_state_dict(SCREAMING_SNAKE_CASE ) A_ : Dict = our_model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE ) A_ : Tuple = ( our_outputs.logits if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else our_outputs.last_hidden_state ) A_ : int = from_model(SCREAMING_SNAKE_CASE ) A_ : List[str] = from_output[-1] if type(SCREAMING_SNAKE_CASE ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: A_ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add model''' , use_temp_dir=SCREAMING_SNAKE_CASE , ) A_ : Optional[int] = 224 if '''seer''' not in name else 384 # we can use the convnext one A_ : Tuple = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' , size=SCREAMING_SNAKE_CASE ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add image processor''' , use_temp_dir=SCREAMING_SNAKE_CASE , ) print(f'''Pushed {name}''' ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True ): A_ : Union[str, Any] = '''imagenet-1k-id2label.json''' A_ : Union[str, Any] = 1_000 A_ : List[str] = (1, num_labels) A_ : List[Any] = '''huggingface/label-files''' A_ : Union[str, Any] = num_labels A_ : Tuple = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='''dataset''' ) ) , '''r''' ) ) A_ : int = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} A_ : str = idalabel A_ : List[str] = {v: k for k, v in idalabel.items()} A_ : Union[str, Any] = partial(SCREAMING_SNAKE_CASE , num_labels=SCREAMING_SNAKE_CASE , idalabel=SCREAMING_SNAKE_CASE , labelaid=SCREAMING_SNAKE_CASE ) A_ : str = { '''regnet-x-002''': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='''x''' ), '''regnet-x-004''': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='''x''' ), '''regnet-x-006''': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='''x''' ), '''regnet-x-008''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='''x''' ), '''regnet-x-016''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='''x''' ), '''regnet-x-032''': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1_008] , groups_width=48 , layer_type='''x''' ), '''regnet-x-040''': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1_360] , groups_width=40 , layer_type='''x''' ), '''regnet-x-064''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1_624] , groups_width=56 , layer_type='''x''' ), '''regnet-x-080''': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1_920] , groups_width=120 , layer_type='''x''' ), '''regnet-x-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 , layer_type='''x''' ), '''regnet-x-160''': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2_048] , groups_width=128 , layer_type='''x''' ), '''regnet-x-320''': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1_344, 2_520] , groups_width=168 , layer_type='''x''' ), # y variant '''regnet-y-002''': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), '''regnet-y-004''': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), '''regnet-y-006''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), '''regnet-y-008''': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), '''regnet-y-016''': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), '''regnet-y-032''': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1_512] , groups_width=24 ), '''regnet-y-040''': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1_088] , groups_width=64 ), '''regnet-y-064''': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1_296] , groups_width=72 ), '''regnet-y-080''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2_016] , groups_width=56 ), '''regnet-y-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 ), '''regnet-y-160''': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1_232, 3_024] , groups_width=112 ), '''regnet-y-320''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 '''regnet-y-320-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer''': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer''': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), # finetuned on imagenet '''regnet-y-320-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer-in1k''': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), } A_ : Dict = NameToOurModelFuncMap() A_ : Optional[Any] = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple[nn.Module, Dict]: A_ : List[Any] = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE , model_dir=str(SCREAMING_SNAKE_CASE ) , map_location='''cpu''' ) A_ : Optional[int] = model_func() # check if we have a head, if yes add it A_ : Dict = files['''classy_state_dict''']['''base_model''']['''model'''] A_ : List[str] = model_state_dict['''trunk'''] model.load_state_dict(SCREAMING_SNAKE_CASE ) return model.eval(), model_state_dict["heads"] # pretrained A_ : List[Any] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) A_ : List[Any] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) A_ : Tuple = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) A_ : Optional[Any] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_2_0.8_3 , w_m=2.5_2 ) ) ) , ) # IN1K finetuned A_ : List[str] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) A_ : str = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) A_ : Union[str, Any] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) A_ : Optional[int] = partial( SCREAMING_SNAKE_CASE , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_2_0.8_3 , w_m=2.5_2 ) ) ) , ) if model_name: convert_weight_and_push( SCREAMING_SNAKE_CASE , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( SCREAMING_SNAKE_CASE , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported regnet* architecture,""" """ currently: regnetx-*, regnety-*. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
186
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 = logging.get_logger(__name__) if is_vision_available(): import PIL class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , )->None: '''simple docstring''' super().__init__(**_SCREAMING_SNAKE_CASE ) A_ : Tuple = size if size is not None else {'''shortest_edge''': 224} A_ : Any = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) A_ : Tuple = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} A_ : Dict = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE , param_name='''crop_size''' ) A_ : str = do_resize A_ : Tuple = size A_ : Optional[Any] = resample A_ : Tuple = do_center_crop A_ : List[Any] = crop_size A_ : Optional[int] = do_rescale A_ : Tuple = rescale_factor A_ : Any = do_normalize A_ : int = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A_ : Any = image_std if image_std is not None else OPENAI_CLIP_STD A_ : Any = do_convert_rgb def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )->np.ndarray: '''simple docstring''' A_ : Dict = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) A_ : Any = get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=size['''shortest_edge'''] , default_to_square=_SCREAMING_SNAKE_CASE ) return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )->np.ndarray: '''simple docstring''' A_ : str = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size['''height'''], size['''width''']) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )->int: '''simple docstring''' return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )->np.ndarray: '''simple docstring''' return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )->PIL.Image.Image: '''simple docstring''' A_ : Optional[int] = do_resize if do_resize is not None else self.do_resize A_ : int = size if size is not None else self.size A_ : Optional[int] = get_size_dict(_SCREAMING_SNAKE_CASE , param_name='''size''' , default_to_square=_SCREAMING_SNAKE_CASE ) A_ : List[Any] = resample if resample is not None else self.resample A_ : Any = do_center_crop if do_center_crop is not None else self.do_center_crop A_ : List[str] = crop_size if crop_size is not None else self.crop_size A_ : int = get_size_dict(_SCREAMING_SNAKE_CASE , param_name='''crop_size''' , default_to_square=_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale A_ : int = rescale_factor if rescale_factor is not None else self.rescale_factor A_ : int = do_normalize if do_normalize is not None else self.do_normalize A_ : Tuple = image_mean if image_mean is not None else self.image_mean A_ : Tuple = image_std if image_std is not None else self.image_std A_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A_ : Optional[int] = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: A_ : List[str] = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. A_ : int = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: A_ : Tuple = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: A_ : Union[str, Any] = [self.center_crop(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: A_ : Tuple = [self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: A_ : List[Any] = [self.normalize(image=_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE ) for image in images] A_ : str = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] A_ : Optional[Any] = {'''pixel_values''': images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
186
1
'''simple docstring''' UpperCamelCase_ : str = [ '''DownloadConfig''', '''DownloadManager''', '''DownloadMode''', '''StreamingDownloadManager''', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
353
'''simple docstring''' import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def __a ( _UpperCamelCase: Dict , _UpperCamelCase: Optional[int] , _UpperCamelCase: List[str] ) -> Optional[Any]: """simple docstring""" return params[F"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def __a ( _UpperCamelCase: List[Any] , _UpperCamelCase: Optional[Any] , _UpperCamelCase: Dict , _UpperCamelCase: Optional[Any]="attention" ) -> Any: """simple docstring""" _snake_case = _snake_case = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) _snake_case = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) _snake_case = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) _snake_case = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) _snake_case = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) _snake_case = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) _snake_case = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) _snake_case = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def __a ( _UpperCamelCase: Tuple , _UpperCamelCase: Optional[int] , _UpperCamelCase: Optional[int] , _UpperCamelCase: Optional[int]=False ) -> List[Any]: """simple docstring""" if split_mlp_wi: _snake_case = params[F"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] _snake_case = params[F"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] _snake_case = (wi_a, wi_a) else: _snake_case = params[F"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] _snake_case = params[F"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def __a ( _UpperCamelCase: Optional[int] , _UpperCamelCase: Dict , _UpperCamelCase: Union[str, Any] , _UpperCamelCase: Union[str, Any] ) -> List[Any]: """simple docstring""" return params[F"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def __a ( _UpperCamelCase: dict , *, _UpperCamelCase: int , _UpperCamelCase: bool , _UpperCamelCase: bool = False ) -> str: """simple docstring""" _snake_case = traverse_util.flatten_dict(variables["target"] ) _snake_case = {"/".join(_UpperCamelCase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _snake_case = "encoder/encoder/mlp/wi_0/kernel" in old print("Split MLP:" , _UpperCamelCase ) _snake_case = collections.OrderedDict() # Shared embeddings. _snake_case = old["token_embedder/embedding"] # Encoder. for i in range(_UpperCamelCase ): # Block i, layer 0 (Self Attention). _snake_case = tax_layer_norm_lookup(_UpperCamelCase , _UpperCamelCase , "encoder" , "pre_attention_layer_norm" ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(_UpperCamelCase , _UpperCamelCase , "encoder" , "attention" ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 1 (MLP). _snake_case = tax_layer_norm_lookup(_UpperCamelCase , _UpperCamelCase , "encoder" , "pre_mlp_layer_norm" ) _snake_case , _snake_case = tax_mlp_lookup(_UpperCamelCase , _UpperCamelCase , "encoder" , _UpperCamelCase ) _snake_case = layer_norm if split_mlp_wi: _snake_case = wi[0].T _snake_case = wi[1].T else: _snake_case = wi.T _snake_case = wo.T if scalable_attention: # convert the rel_embedding of each layer _snake_case = tax_relpos_bias_lookup( _UpperCamelCase , _UpperCamelCase , "encoder" ).T _snake_case = old["encoder/encoder_norm/scale"] if not scalable_attention: _snake_case = tax_relpos_bias_lookup( _UpperCamelCase , 0 , "encoder" ).T _snake_case = tax_relpos_bias_lookup( _UpperCamelCase , 0 , "decoder" ).T if not is_encoder_only: # Decoder. for i in range(_UpperCamelCase ): # Block i, layer 0 (Self Attention). _snake_case = tax_layer_norm_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , "pre_self_attention_layer_norm" ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , "self_attention" ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 1 (Cross Attention). _snake_case = tax_layer_norm_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , "pre_cross_attention_layer_norm" ) _snake_case , _snake_case , _snake_case , _snake_case = tax_attention_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , "encoder_decoder_attention" ) _snake_case = layer_norm _snake_case = k.T _snake_case = o.T _snake_case = q.T _snake_case = v.T # Block i, layer 2 (MLP). _snake_case = tax_layer_norm_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , "pre_mlp_layer_norm" ) _snake_case , _snake_case = tax_mlp_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" , _UpperCamelCase ) _snake_case = layer_norm if split_mlp_wi: _snake_case = wi[0].T _snake_case = wi[1].T else: _snake_case = wi.T _snake_case = wo.T if scalable_attention: # convert the rel_embedding of each layer _snake_case = tax_relpos_bias_lookup(_UpperCamelCase , _UpperCamelCase , "decoder" ).T _snake_case = old["decoder/decoder_norm/scale"] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _snake_case = old["decoder/logits_dense/kernel"].T return new def __a ( _UpperCamelCase: Any , _UpperCamelCase: bool ) -> Dict: """simple docstring""" _snake_case = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _snake_case = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _snake_case = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) _snake_case = state_dict["shared.weight"] return state_dict def __a ( _UpperCamelCase: str , _UpperCamelCase: List[str] , _UpperCamelCase: Any , _UpperCamelCase: str , _UpperCamelCase: List[Any] ) -> Dict: """simple docstring""" _snake_case = checkpoints.load_tax_checkpoint(_UpperCamelCase ) _snake_case = convert_tax_to_pytorch( _UpperCamelCase , num_layers=config.num_layers , is_encoder_only=_UpperCamelCase , scalable_attention=_UpperCamelCase ) _snake_case = make_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) def __a ( _UpperCamelCase: Union[str, Any] , _UpperCamelCase: Union[str, Any] , _UpperCamelCase: Optional[Any] , _UpperCamelCase: bool = False , _UpperCamelCase: bool = False , ) -> Dict: """simple docstring""" _snake_case = MTaConfig.from_json_file(_UpperCamelCase ) print(F"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _snake_case = UMTaEncoderModel(_UpperCamelCase ) else: _snake_case = UMTaForConditionalGeneration(_UpperCamelCase ) # Load weights from tf checkpoint load_tax_weights_in_ta(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(_UpperCamelCase ) # Verify that we can load the checkpoint. model.from_pretrained(_UpperCamelCase ) print("Done" ) if __name__ == "__main__": UpperCamelCase_ : Any = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) UpperCamelCase_ : Union[str, Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
142
0
'''simple docstring''' from collections.abc import Iterable from typing import Any class lowerCAmelCase_ : def __init__( self , _lowerCAmelCase = None ) -> Dict: _lowerCAmelCase = value _lowerCAmelCase = None # Added in order to delete a node easier _lowerCAmelCase = None _lowerCAmelCase = None def __repr__( self ) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({f'''{self.value}''': (self.left, self.right)} , indent=1 ) class lowerCAmelCase_ : def __init__( self , _lowerCAmelCase = None ) -> Any: _lowerCAmelCase = root def __str__( self ) -> int: return str(self.root ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: if new_children is not None: # reset its kids _lowerCAmelCase = node.parent if node.parent is not None: # reset its parent if self.is_right(snake_case_ ): # If it is the right children _lowerCAmelCase = new_children else: _lowerCAmelCase = new_children else: _lowerCAmelCase = new_children def _snake_case ( self , _lowerCAmelCase ) -> int: if node.parent and node.parent.right: return node == node.parent.right return False def _snake_case ( self ) -> Union[str, Any]: return self.root is None def _snake_case ( self , _lowerCAmelCase ) -> List[Any]: _lowerCAmelCase = Node(snake_case_ ) # create a new Node if self.empty(): # if Tree is empty _lowerCAmelCase = new_node # set its root else: # Tree is not empty _lowerCAmelCase = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: _lowerCAmelCase = new_node # We insert the new node in a leaf break else: _lowerCAmelCase = parent_node.left else: if parent_node.right is None: _lowerCAmelCase = new_node break else: _lowerCAmelCase = parent_node.right _lowerCAmelCase = parent_node def _snake_case ( self , *_lowerCAmelCase ) -> List[Any]: for value in values: self.__insert(snake_case_ ) def _snake_case ( self , _lowerCAmelCase ) -> List[str]: if self.empty(): raise IndexError("Warning: Tree is empty! please use another." ) else: _lowerCAmelCase = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: _lowerCAmelCase = node.left if value < node.value else node.right return node def _snake_case ( self , _lowerCAmelCase = None ) -> str: if node is None: if self.root is None: return None _lowerCAmelCase = self.root if not self.empty(): while node.right is not None: _lowerCAmelCase = node.right return node def _snake_case ( self , _lowerCAmelCase = None ) -> str: if node is None: _lowerCAmelCase = self.root if self.root is None: return None if not self.empty(): _lowerCAmelCase = self.root while node.left is not None: _lowerCAmelCase = node.left return node def _snake_case ( self , _lowerCAmelCase ) -> Dict: _lowerCAmelCase = self.search(snake_case_ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(snake_case_ , snake_case_ ) elif node.left is None: # Has only right children self.__reassign_nodes(snake_case_ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(snake_case_ , node.left ) else: _lowerCAmelCase = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore _lowerCAmelCase = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def _snake_case ( self , _lowerCAmelCase ) -> Dict: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def _snake_case ( self , _lowerCAmelCase=None ) -> List[Any]: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> Tuple: if node: self.inorder(snake_case_ , node.left ) arr.append(node.value ) self.inorder(snake_case_ , node.right ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: _lowerCAmelCase = [] self.inorder(snake_case_ , snake_case_ ) # append all values to list using inorder traversal return arr[k - 1] def __a(SCREAMING_SNAKE_CASE_ : List[str] ): '''simple docstring''' _lowerCAmelCase = [] if curr_node is not None: _lowerCAmelCase = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def __a(): '''simple docstring''' _lowerCAmelCase = (8, 3, 6, 1, 10, 14, 13, 4, 7) _lowerCAmelCase = BinarySearchTree() for i in testlist: t.insert(_UpperCAmelCase ) # Prints all the elements of the list in order traversal print(_UpperCAmelCase ) if t.search(6 ) is not None: print("The value 6 exists" ) else: print("The value 6 doesn\'t exist" ) if t.search(-1 ) is not None: print("The value -1 exists" ) else: print("The value -1 doesn\'t exist" ) if not t.empty(): print("Max Value: " , t.get_max().value ) # type: ignore print("Min Value: " , t.get_min().value ) # type: ignore for i in testlist: t.remove(_UpperCAmelCase ) print(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
158
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' lowercase_ : Dict = ["""image_processor""", """tokenizer"""] lowercase_ : Union[str, Any] = """ViltImageProcessor""" lowercase_ : Any = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self , snake_case_=None , snake_case_=None , **snake_case_ ): """simple docstring""" A_ : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , snake_case_ , ) A_ : Dict = kwargs.pop('feature_extractor' ) A_ : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(snake_case_ , snake_case_ ) A_ : List[str] = self.image_processor def __call__( self , snake_case_ , snake_case_ = None , snake_case_ = True , snake_case_ = False , snake_case_ = None , snake_case_ = None , snake_case_ = 0 , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = True , snake_case_ = None , **snake_case_ , ): """simple docstring""" A_ : str = self.tokenizer( text=snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , stride=snake_case_ , pad_to_multiple_of=snake_case_ , return_token_type_ids=snake_case_ , return_attention_mask=snake_case_ , return_overflowing_tokens=snake_case_ , return_special_tokens_mask=snake_case_ , return_offsets_mapping=snake_case_ , return_length=snake_case_ , verbose=snake_case_ , return_tensors=snake_case_ , **snake_case_ , ) # add pixel_values + pixel_mask A_ : Optional[int] = self.image_processor(snake_case_ , return_tensors=snake_case_ ) encoding.update(snake_case_ ) return encoding def lowerCamelCase_ ( self , *snake_case_ , **snake_case_ ): """simple docstring""" return self.tokenizer.batch_decode(*snake_case_ , **snake_case_ ) def lowerCamelCase_ ( self , *snake_case_ , **snake_case_ ): """simple docstring""" return self.tokenizer.decode(*snake_case_ , **snake_case_ ) @property def lowerCamelCase_ ( self ): """simple docstring""" A_ : Any = self.tokenizer.model_input_names A_ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCamelCase_ ( self ): """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case_ , ) return self.image_processor_class @property def lowerCamelCase_ ( self ): """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case_ , ) return self.image_processor
286
0
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int _UpperCAmelCase : List[Any] = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowercase ( datasets.BuilderConfig ): __lowercase : Optional[datasets.Features] = None def A ( lowercase , lowercase , ) -> Dict: '''simple docstring''' import pyspark def generate_fn(): UpperCamelCase = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: UpperCamelCase = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) UpperCamelCase = partition_df.collect() UpperCamelCase = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class lowercase ( _BaseExamplesIterable ): def __init__( self , A_ , A_=None , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = df UpperCamelCase = partition_order or range(self.df.rdd.getNumPartitions() ) UpperCamelCase = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Any: """simple docstring""" yield from self.generate_examples_fn() def __UpperCamelCase ( self , A_ ) -> "SparkExamplesIterable": """simple docstring""" UpperCamelCase = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(A_ ) return SparkExamplesIterable(self.df , partition_order=A_ ) def __UpperCamelCase ( self , A_ , A_ ) -> "SparkExamplesIterable": """simple docstring""" UpperCamelCase = self.split_shard_indices_by_worker(A_ , A_ ) return SparkExamplesIterable(self.df , partition_order=A_ ) @property def __UpperCamelCase ( self ) -> int: """simple docstring""" return len(self.partition_order ) class lowercase ( datasets.DatasetBuilder ): __lowercase : int = SparkConfig def __init__( self , A_ , A_ = None , A_ = None , **A_ , ) -> Any: """simple docstring""" import pyspark UpperCamelCase = pyspark.sql.SparkSession.builder.getOrCreate() UpperCamelCase = df UpperCamelCase = working_dir super().__init__( cache_dir=A_ , config_name=str(self.df.semanticHash() ) , **A_ , ) def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" # Returns the path of the created file. def create_cache_and_write_probe(A_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=A_ ) UpperCamelCase = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(A_ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: UpperCamelCase = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(A_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __UpperCamelCase ( self , A_ ) -> str: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __UpperCamelCase ( self , A_ ) -> Optional[Any]: """simple docstring""" import pyspark def get_arrow_batch_size(A_ ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) UpperCamelCase = self.df.count() UpperCamelCase = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. UpperCamelCase = ( self.df.limit(A_ ) .repartition(1 ) .mapInArrow(A_ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) UpperCamelCase = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. UpperCamelCase = min(A_ , int(approx_total_size / max_shard_size ) ) UpperCamelCase = self.df.repartition(A_ ) def __UpperCamelCase ( self , A_ , A_ , A_ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: """simple docstring""" import pyspark UpperCamelCase = ParquetWriter if file_format == 'parquet' else ArrowWriter UpperCamelCase = os.path.join(self._working_dir , os.path.basename(A_ ) ) if self._working_dir else fpath UpperCamelCase = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. UpperCamelCase = self.config.features UpperCamelCase = self._writer_batch_size UpperCamelCase = self._fs.storage_options def write_arrow(A_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. UpperCamelCase = pyspark.TaskContext().taskAttemptId() UpperCamelCase = next(A_ , A_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) UpperCamelCase = 0 UpperCamelCase = writer_class( features=A_ , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=A_ , storage_options=A_ , embed_local_files=A_ , ) UpperCamelCase = pa.Table.from_batches([first_batch] ) writer.write_table(A_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: UpperCamelCase , UpperCamelCase = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 UpperCamelCase = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=A_ , storage_options=A_ , embed_local_files=A_ , ) UpperCamelCase = pa.Table.from_batches([batch] ) writer.write_table(A_ ) if writer._num_bytes > 0: UpperCamelCase , UpperCamelCase = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(A_ ) ): UpperCamelCase = os.path.join(os.path.dirname(A_ ) , os.path.basename(A_ ) ) shutil.move(A_ , A_ ) UpperCamelCase = ( self.df.mapInArrow(A_ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __UpperCamelCase ( self , A_ , A_ = "arrow" , A_ = None , A_ = None , **A_ , ) -> List[Any]: """simple docstring""" self._validate_cache_dir() UpperCamelCase = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(A_ ) UpperCamelCase = not is_remote_filesystem(self._fs ) UpperCamelCase = os.path.join if is_local else posixpath.join UpperCamelCase = '-TTTTT-SSSSS-of-NNNNN' UpperCamelCase = F'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' UpperCamelCase = path_join(self._output_dir , A_ ) UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = [] UpperCamelCase = [] for task_id, content in self._prepare_split_single(A_ , A_ , A_ ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(A_ ) UpperCamelCase = total_num_examples UpperCamelCase = total_num_bytes # should rename everything at the end logger.debug(F'''Renaming {total_shards} shards.''' ) if total_shards > 1: UpperCamelCase = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. UpperCamelCase = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( A_ , A_ , A_ , ): rename( A_ , fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , F'''{global_shard_id:05d}''' ).replace('NNNNN' , F'''{total_shards:05d}''' ) , ) UpperCamelCase = [] UpperCamelCase = 0 for i in range(len(A_ ) ): UpperCamelCase , UpperCamelCase = task_id_and_num_shards[i] for shard_id in range(A_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(A_ , len(A_ ) ).map(lambda A_ : _rename_shard(*A_ ) ).collect() else: # don't use any pattern UpperCamelCase = 0 UpperCamelCase = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace(A_ , '' ) , ) def __UpperCamelCase ( self , A_ , ) -> SparkExamplesIterable: """simple docstring""" return SparkExamplesIterable(self.df )
361
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline _UpperCAmelCase : Optional[Any] = { "n_samples": 64, "horizon": 32, "num_inference_steps": 20, "n_guide_steps": 2, # can set to 0 for faster sampling, does not use value network "scale_grad_by_std": True, "scale": 0.1, "eta": 0.0, "t_grad_cutoff": 2, "device": "cpu", } if __name__ == "__main__": _UpperCAmelCase : int = "hopper-medium-v2" _UpperCAmelCase : Tuple = gym.make(env_name) _UpperCAmelCase : Any = ValueGuidedRLPipeline.from_pretrained( "bglick13/hopper-medium-v2-value-function-hor32", env=env, ) env.seed(0) _UpperCAmelCase : Optional[Any] = env.reset() _UpperCAmelCase : Union[str, Any] = 0 _UpperCAmelCase : Union[str, Any] = 0 _UpperCAmelCase : Dict = 1_000 _UpperCAmelCase : Tuple = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy _UpperCAmelCase : int = pipeline(obs, planning_horizon=32) # execute action in environment _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase : List[Any] = env.step(denorm_actions) _UpperCAmelCase : int = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( F'''Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:''' F''' {total_score}''' ) # save observations for rendering rollout.append(next_observation.copy()) _UpperCAmelCase : Union[str, Any] = next_observation except KeyboardInterrupt: pass print(F'''Total reward: {total_reward}''')
110
0
"""simple docstring""" import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient __A = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> Union[str, Any]: lowercase__: List[str] = test_results.split(''' ''' ) lowercase__: Dict = 0 lowercase__: str = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. lowercase__: int = expressions[-2] if '''=''' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowerCAmelCase__ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> List[str]: lowercase__: int = {} lowercase__: Optional[Any] = None lowercase__: Any = False for line in failures_short_lines.split('''\n''' ): if re.search(R'''_ \[doctest\]''' , lowerCAmelCase__ ): lowercase__: Union[str, Any] = True lowercase__: Union[str, Any] = line.split(''' ''' )[2] elif in_error and not line.split(''' ''' )[0].isdigit(): lowercase__: Optional[Any] = line lowercase__: List[Any] = False return failures class UpperCAmelCase : """simple docstring""" def __init__( self , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: Union[str, Any] = title lowercase__: Optional[Any] = doc_test_results['''time_spent'''].split(''',''' )[0] lowercase__: Tuple = doc_test_results['''success'''] lowercase__: List[str] = doc_test_results['''failures'''] lowercase__: str = self.n_success + self.n_failures # Failures and success of the modeling tests lowercase__: Any = doc_test_results @property def _snake_case ( self ): lowercase__: Dict = [self._time_spent] lowercase__: Dict = 0 for time in time_spent: lowercase__: List[str] = time.split(''':''' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(snake_case_ ) == 1: lowercase__: Optional[int] = [0, 0, time_parts[0]] lowercase__: Optional[int] = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3600 + minutes * 60 + seconds lowercase__: List[str] = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F"""{int(snake_case_ )}h{int(snake_case_ )}m{int(snake_case_ )}s""" @property def _snake_case ( self ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def _snake_case ( self ): return { "type": "section", "text": { "type": "plain_text", "text": F"""🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.""", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } @property def _snake_case ( self ): return { "type": "section", "text": { "type": "plain_text", "text": ( F"""There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in""" F""" {self.time}.""" ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } @property def _snake_case ( self ): lowercase__: List[str] = 40 lowercase__: List[str] = {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(snake_case_ , snake_case_ )} lowercase__: int = '''''' for category, failures in category_failures.items(): if len(snake_case_ ) == 0: continue if report != "": report += "\n\n" report += F"""*{category} failures*:""".ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(snake_case_ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"""The following examples had failures:\n\n\n{report}\n""", }, } @property def _snake_case ( self ): lowercase__: List[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(snake_case_ ) @staticmethod def _snake_case ( ): lowercase__: Optional[int] = [ { '''type''': '''section''', '''text''': { '''type''': '''plain_text''', '''text''': '''There was an issue running the tests.''', }, '''accessory''': { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True}, '''url''': F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } ] print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(snake_case_ )} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text='''There was an issue running the tests.''' , blocks=snake_case_ , ) def _snake_case ( self ): print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(self.payload )} ) ) lowercase__: Any = F"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else '''All tests passed.''' lowercase__: Dict = client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , blocks=self.payload , text=snake_case_ , ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: List[str] = '''''' for key, value in failures.items(): lowercase__: Any = value[:200] + ''' [Truncated]''' if len(snake_case_ ) > 250 else value failures_text += F"""*{key}*\n_{value}_\n\n""" lowercase__: Dict = job_name lowercase__: Dict = {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}} if job_link is not None: lowercase__: List[str] = { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''GitHub Action job''', '''emoji''': True}, '''url''': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def _snake_case ( self ): if self.thread_ts is None: raise ValueError('''Can only post reply if a post has been made.''' ) lowercase__: Any = self.doc_test_results.pop('''job_link''' ) self.doc_test_results.pop('''failures''' ) self.doc_test_results.pop('''success''' ) self.doc_test_results.pop('''time_spent''' ) lowercase__: str = sorted(self.doc_test_results.items() , key=lambda _UpperCAmelCase : t[0] ) for job, job_result in sorted_dict: if len(job_result['''failures'''] ): lowercase__: Optional[Any] = F"""*Num failures* :{len(job_result['failed'] )} \n""" lowercase__: List[Any] = job_result['''failures'''] lowercase__: int = self.get_reply_blocks(snake_case_ , snake_case_ , snake_case_ , text=snake_case_ ) print('''Sending the following reply''' ) print(json.dumps({'''blocks''': blocks} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text=F"""Results for {job}""" , blocks=snake_case_ , thread_ts=self.thread_ts['''ts'''] , ) time.sleep(1 ) def SCREAMING_SNAKE_CASE__ ( ) -> Optional[Any]: lowercase__: int = os.environ['''GITHUB_RUN_ID'''] lowercase__: Union[str, Any] = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100""" lowercase__: Optional[int] = requests.get(lowerCAmelCase__ ).json() lowercase__: List[Any] = {} try: jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) lowercase__: Optional[Any] = math.ceil((result['''total_count'''] - 1_0_0) / 1_0_0 ) for i in range(lowerCAmelCase__ ): lowercase__: Any = requests.get(url + F"""&page={i + 2}""" ).json() jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return jobs except Exception as e: print('''Unknown error, could not fetch links.''' , lowerCAmelCase__ ) return {} def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> Dict: lowercase__: int = {} if os.path.exists(lowerCAmelCase__ ): lowercase__: List[Any] = os.listdir(lowerCAmelCase__ ) for file in files: try: with open(os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , encoding='''utf-8''' ) as f: lowercase__: Optional[Any] = f.read() except UnicodeDecodeError as e: raise ValueError(F"""Could not open {os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )}.""" ) from e return _artifact def SCREAMING_SNAKE_CASE__ ( ) -> Optional[Any]: class UpperCAmelCase : """simple docstring""" def __init__( self , _UpperCAmelCase ): lowercase__: Optional[int] = name lowercase__: int = [] def __str__( self ): return self.name def _snake_case ( self , _UpperCAmelCase ): self.paths.append({'''name''': self.name, '''path''': path} ) lowercase__: Dict[str, Artifact] = {} lowercase__: Tuple = filter(os.path.isdir , os.listdir() ) for directory in directories: lowercase__: Tuple = directory if artifact_name not in _available_artifacts: lowercase__: str = Artifact(lowerCAmelCase__ ) _available_artifacts[artifact_name].add_path(lowerCAmelCase__ ) return _available_artifacts if __name__ == "__main__": __A = get_job_links() __A = retrieve_available_artifacts() __A = collections.OrderedDict( [ ("*.py", "API Examples"), ("*.md", "MD Examples"), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' __A = { v: { "failed": [], "failures": {}, } for v in docs.values() } # Link to the GitHub Action job __A = github_actions_job_links.get("run_doctests") __A = available_artifacts["doc_tests_gpu_test_reports"].paths[0] __A = retrieve_artifact(artifact_path["name"]) if "stats" in artifact: __A ,__A ,__A = handle_test_results(artifact["stats"]) __A = failed __A = success __A = time_spent[1:-1] + ", " __A = extract_first_line_failure(artifact["failures_short"]) for line in artifact["summary_short"].split("\n"): if re.search("FAILED", line): __A = line.replace("FAILED ", "") __A = line.split()[0].replace("\n", "") if "::" in line: __A ,__A = line.split("::") else: __A ,__A = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): __A = docs[file_regex] doc_test_results[category]["failed"].append(test) __A = all_failures[test] if test in all_failures else "N/A" __A = failure break __A = Message("🤗 Results of the doc tests.", doc_test_results) message.post() message.post_reply()
177
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def __UpperCamelCase ( lowerCAmelCase__ : Any ): # vision encoder if "img_encoder.pos_embed" in name: __a : Any = name.replace('''img_encoder.pos_embed''' , '''vision_model.embeddings.position_embeddings''' ) if "img_encoder.patch_embed.proj" in name: __a : str = name.replace('''img_encoder.patch_embed.proj''' , '''vision_model.embeddings.patch_embeddings.projection''' ) if "img_encoder.patch_embed.norm" in name: __a : int = name.replace('''img_encoder.patch_embed.norm''' , '''vision_model.embeddings.layernorm''' ) if "img_encoder.layers" in name: __a : Union[str, Any] = name.replace('''img_encoder.layers''' , '''vision_model.encoder.stages''' ) if "blocks" in name and "res" not in name: __a : List[Any] = name.replace('''blocks''' , '''layers''' ) if "attn" in name and "pre_assign" not in name: __a : Tuple = name.replace('''attn''' , '''self_attn''' ) if "proj" in name and "self_attn" in name and "text" not in name: __a : List[Any] = name.replace('''proj''' , '''out_proj''' ) if "pre_assign_attn.attn.proj" in name: __a : Any = name.replace('''pre_assign_attn.attn.proj''' , '''pre_assign_attn.attn.out_proj''' ) if "norm1" in name: __a : Union[str, Any] = name.replace('''norm1''' , '''layer_norm1''' ) if "norm2" in name and "pre_assign" not in name: __a : Optional[int] = name.replace('''norm2''' , '''layer_norm2''' ) if "img_encoder.norm" in name: __a : Union[str, Any] = name.replace('''img_encoder.norm''' , '''vision_model.layernorm''' ) # text encoder if "text_encoder.token_embedding" in name: __a : List[Any] = name.replace('''text_encoder.token_embedding''' , '''text_model.embeddings.token_embedding''' ) if "text_encoder.positional_embedding" in name: __a : Any = name.replace('''text_encoder.positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "text_encoder.transformer.resblocks." in name: __a : Any = name.replace('''text_encoder.transformer.resblocks.''' , '''text_model.encoder.layers.''' ) if "ln_1" in name: __a : str = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __a : Union[str, Any] = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __a : Union[str, Any] = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __a : Union[str, Any] = name.replace('''c_proj''' , '''fc2''' ) if "text_encoder" in name: __a : Optional[int] = name.replace('''text_encoder''' , '''text_model''' ) if "ln_final" in name: __a : str = name.replace('''ln_final''' , '''final_layer_norm''' ) # projection layers if "img_projector.linear_hidden." in name: __a : List[str] = name.replace('''img_projector.linear_hidden.''' , '''visual_projection.''' ) if "img_projector.linear_out." in name: __a : str = name.replace('''img_projector.linear_out.''' , '''visual_projection.3.''' ) if "text_projector.linear_hidden" in name: __a : int = name.replace('''text_projector.linear_hidden''' , '''text_projection''' ) if "text_projector.linear_out" in name: __a : List[str] = name.replace('''text_projector.linear_out''' , '''text_projection.3''' ) return name def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Tuple ): for key in orig_state_dict.copy().keys(): __a : List[Any] = orig_state_dict.pop(lowerCAmelCase__ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a : Tuple = key.split('''.''' ) __a , __a : List[Any] = int(key_split[2] ), int(key_split[4] ) __a : List[Any] = config.vision_config.hidden_size if "weight" in key: __a : int = val[:dim, :] __a : List[str] = val[dim : dim * 2, :] __a : List[Any] = val[-dim:, :] else: __a : List[str] = val[:dim] __a : int = val[dim : dim * 2] __a : Any = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a : int = key.split('''.''' ) __a : str = int(key_split[3] ) __a : List[Any] = config.text_config.hidden_size if "weight" in key: __a : List[str] = val[:dim, :] __a : Any = val[ dim : dim * 2, : ] __a : Dict = val[-dim:, :] else: __a : List[str] = val[:dim] __a : Any = val[dim : dim * 2] __a : Any = val[-dim:] else: __a : Union[str, Any] = rename_key(lowerCAmelCase__ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): __a : List[Any] = val.squeeze_() else: __a : Dict = val return orig_state_dict def __UpperCamelCase ( ): __a : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __a : str = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def __UpperCamelCase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any]="groupvit-gcc-yfcc" , lowerCAmelCase__ : int=False ): __a : Union[str, Any] = GroupViTConfig() __a : int = GroupViTModel(lowerCAmelCase__ ).eval() __a : Any = torch.load(lowerCAmelCase__ , map_location='''cpu''' )['''model'''] __a : Optional[Any] = convert_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) __a , __a : Dict = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowerCAmelCase__ ) == 0) # verify result __a : Any = CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) __a : Optional[Any] = prepare_img() __a : Optional[int] = processor(text=['''a photo of a cat''', '''a photo of a dog'''] , images=lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors='''pt''' ) with torch.no_grad(): __a : Tuple = model(**lowerCAmelCase__ ) if model_name == "groupvit-gcc-yfcc": __a : List[str] = torch.tensor([[13.35_23, 6.36_29]] ) elif model_name == "groupvit-gcc-redcaps": __a : List[str] = torch.tensor([[16.18_73, 8.62_30]] ) else: raise ValueError(f"Model name {model_name} not supported." ) assert torch.allclose(outputs.logits_per_image , lowerCAmelCase__ , atol=1e-3 ) processor.save_pretrained(lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) print('''Successfully saved processor and model to''' , lowerCAmelCase__ ) if push_to_hub: print('''Pushing to the hub...''' ) processor.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) model.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) if __name__ == "__main__": lowercase__ =argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.' ) parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint') parser.add_argument( '--model_name', default='groupvit-gccy-fcc', type=str, help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.', ) lowercase__ =parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
216
0
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder UpperCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase_ = 256 class lowerCamelCase__( __lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = ['melgan'] def __init__( self: Optional[Any] , UpperCamelCase_: SpectrogramNotesEncoder , UpperCamelCase_: SpectrogramContEncoder , UpperCamelCase_: TaFilmDecoder , UpperCamelCase_: DDPMScheduler , UpperCamelCase_: OnnxRuntimeModel if is_onnx_available() else Any , ): super().__init__() # From MELGAN __lowerCamelCase = math.log(1E-5 ) # Matches MelGAN training. __lowerCamelCase = 4.0 # Largest value for most examples __lowerCamelCase = 1_28 self.register_modules( notes_encoder=UpperCamelCase_ , continuous_encoder=UpperCamelCase_ , decoder=UpperCamelCase_ , scheduler=UpperCamelCase_ , melgan=UpperCamelCase_ , ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Tuple , UpperCamelCase_: int=(-1.0, 1.0) , UpperCamelCase_: Union[str, Any]=False ): __lowerCamelCase, __lowerCamelCase = output_range if clip: __lowerCamelCase = torch.clip(UpperCamelCase_ , self.min_value , self.max_value ) # Scale to [0, 1]. __lowerCamelCase = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def lowerCAmelCase__ ( self: int , UpperCamelCase_: Optional[int] , UpperCamelCase_: List[Any]=(-1.0, 1.0) , UpperCamelCase_: Dict=False ): __lowerCamelCase, __lowerCamelCase = input_range __lowerCamelCase = torch.clip(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if clip else outputs # Scale to [0, 1]. __lowerCamelCase = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def lowerCAmelCase__ ( self: Dict , UpperCamelCase_: Any , UpperCamelCase_: Any , UpperCamelCase_: Dict ): __lowerCamelCase = input_tokens > 0 __lowerCamelCase, __lowerCamelCase = self.notes_encoder( encoder_input_tokens=UpperCamelCase_ , encoder_inputs_mask=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase = self.continuous_encoder( encoder_inputs=UpperCamelCase_ , encoder_inputs_mask=UpperCamelCase_ ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def lowerCAmelCase__ ( self: Union[str, Any] , UpperCamelCase_: str , UpperCamelCase_: Dict , UpperCamelCase_: Optional[int] ): __lowerCamelCase = noise_time if not torch.is_tensor(UpperCamelCase_ ): __lowerCamelCase = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(UpperCamelCase_ ) and len(timesteps.shape ) == 0: __lowerCamelCase = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __lowerCamelCase = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) __lowerCamelCase = self.decoder( encodings_and_masks=UpperCamelCase_ , decoder_input_tokens=UpperCamelCase_ , decoder_noise_time=UpperCamelCase_ ) return logits @torch.no_grad() def __call__( self: List[Any] , UpperCamelCase_: List[List[int]] , UpperCamelCase_: Optional[torch.Generator] = None , UpperCamelCase_: int = 1_00 , UpperCamelCase_: bool = True , UpperCamelCase_: str = "numpy" , UpperCamelCase_: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCamelCase_: int = 1 , ): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(UpperCamelCase_ )}.' ) __lowerCamelCase = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) __lowerCamelCase = np.zeros([1, 0, self.n_dims] , np.floataa ) __lowerCamelCase = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase_ , device=self.device ) for i, encoder_input_tokens in enumerate(UpperCamelCase_ ): if i == 0: __lowerCamelCase = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. __lowerCamelCase = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase_ , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. __lowerCamelCase = ones __lowerCamelCase = self.scale_features( UpperCamelCase_ , output_range=[-1.0, 1.0] , clip=UpperCamelCase_ ) __lowerCamelCase = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=UpperCamelCase_ , continuous_mask=UpperCamelCase_ , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop __lowerCamelCase = randn_tensor( shape=encoder_continuous_inputs.shape , generator=UpperCamelCase_ , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(UpperCamelCase_ ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __lowerCamelCase = self.decode( encodings_and_masks=UpperCamelCase_ , input_tokens=UpperCamelCase_ , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 __lowerCamelCase = self.scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ ).prev_sample __lowerCamelCase = self.scale_to_features(UpperCamelCase_ , input_range=[-1.0, 1.0] ) __lowerCamelCase = mel[:1] __lowerCamelCase = mel.cpu().float().numpy() __lowerCamelCase = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCamelCase_ , UpperCamelCase_ ) logger.info("""Generated segment""" , UpperCamelCase_ ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" ) elif output_type == "numpy" and self.melgan is None: raise ValueError( """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" ) if output_type == "numpy": __lowerCamelCase = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: __lowerCamelCase = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=UpperCamelCase_ )
370
import string import numpy def lowerCamelCase__ ( A__ : int , A__ : int ): '''simple docstring''' return b if a == 0 else greatest_common_divisor(b % a , A__ ) class lowerCamelCase__: UpperCAmelCase__ : Optional[int] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) UpperCAmelCase__ : Optional[int] = numpy.vectorize(lambda __lowerCamelCase: x % 36) UpperCAmelCase__ : List[Any] = numpy.vectorize(__lowerCamelCase) def __init__( self: List[Any] , UpperCamelCase_: numpy.ndarray ): __lowerCamelCase = self.modulus(UpperCamelCase_ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key __lowerCamelCase = encrypt_key.shape[0] def lowerCAmelCase__ ( self: str , UpperCamelCase_: str ): return self.key_string.index(UpperCamelCase_ ) def lowerCAmelCase__ ( self: str , UpperCamelCase_: int ): return self.key_string[round(UpperCamelCase_ )] def lowerCAmelCase__ ( self: Tuple ): __lowerCamelCase = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __lowerCamelCase = det % len(self.key_string ) __lowerCamelCase = len(self.key_string ) if greatest_common_divisor(UpperCamelCase_ , len(self.key_string ) ) != 1: __lowerCamelCase = ( F'determinant modular {req_l} of encryption key({det}) ' F'is not co prime w.r.t {req_l}.\nTry another key.' ) raise ValueError(UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: str ): __lowerCamelCase = [char for char in text.upper() if char in self.key_string] __lowerCamelCase = chars[-1] while len(UpperCamelCase_ ) % self.break_key != 0: chars.append(UpperCamelCase_ ) return "".join(UpperCamelCase_ ) def lowerCAmelCase__ ( self: Optional[Any] , UpperCamelCase_: str ): __lowerCamelCase = self.process_text(text.upper() ) __lowerCamelCase = """""" for i in range(0 , len(UpperCamelCase_ ) - self.break_key + 1 , self.break_key ): __lowerCamelCase = text[i : i + self.break_key] __lowerCamelCase = [self.replace_letters(UpperCamelCase_ ) for char in batch] __lowerCamelCase = numpy.array([vec] ).T __lowerCamelCase = self.modulus(self.encrypt_key.dot(UpperCamelCase_ ) ).T.tolist()[ 0 ] __lowerCamelCase = """""".join( self.replace_digits(UpperCamelCase_ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase__ ( self: List[str] ): __lowerCamelCase = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: __lowerCamelCase = det % len(self.key_string ) __lowerCamelCase = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: __lowerCamelCase = i break __lowerCamelCase = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCamelCase_ ) ) def lowerCAmelCase__ ( self: Optional[Any] , UpperCamelCase_: str ): __lowerCamelCase = self.make_decrypt_key() __lowerCamelCase = self.process_text(text.upper() ) __lowerCamelCase = """""" for i in range(0 , len(UpperCamelCase_ ) - self.break_key + 1 , self.break_key ): __lowerCamelCase = text[i : i + self.break_key] __lowerCamelCase = [self.replace_letters(UpperCamelCase_ ) for char in batch] __lowerCamelCase = numpy.array([vec] ).T __lowerCamelCase = self.modulus(decrypt_key.dot(UpperCamelCase_ ) ).T.tolist()[0] __lowerCamelCase = """""".join( self.replace_digits(UpperCamelCase_ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCamelCase__ ( ): '''simple docstring''' __lowerCamelCase = int(input("""Enter the order of the encryption key: """ ) ) __lowerCamelCase = [] print("""Enter each row of the encryption key with space separated integers""" ) for _ in range(A__ ): __lowerCamelCase = [int(A__ ) for x in input().split()] hill_matrix.append(A__ ) __lowerCamelCase = HillCipher(numpy.array(A__ ) ) print("""Would you like to encrypt or decrypt some text? (1 or 2)""" ) __lowerCamelCase = input("""\n1. Encrypt\n2. Decrypt\n""" ) if option == "1": __lowerCamelCase = input("""What text would you like to encrypt?: """ ) print("""Your encrypted text is:""" ) print(hc.encrypt(A__ ) ) elif option == "2": __lowerCamelCase = input("""What text would you like to decrypt?: """ ) print("""Your decrypted text is:""" ) print(hc.decrypt(A__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
29
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
122
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def lowerCamelCase__ ( a__ : Any , a__ : Union[str, Any] ) -> int: UpperCamelCase_ = checkpoint UpperCamelCase_ = {} UpperCamelCase_ = vae_state_dict["""encoder.conv_in.weight"""] UpperCamelCase_ = vae_state_dict["""encoder.conv_in.bias"""] UpperCamelCase_ = vae_state_dict["""encoder.conv_out.weight"""] UpperCamelCase_ = vae_state_dict["""encoder.conv_out.bias"""] UpperCamelCase_ = vae_state_dict["""encoder.norm_out.weight"""] UpperCamelCase_ = vae_state_dict["""encoder.norm_out.bias"""] UpperCamelCase_ = vae_state_dict["""decoder.conv_in.weight"""] UpperCamelCase_ = vae_state_dict["""decoder.conv_in.bias"""] UpperCamelCase_ = vae_state_dict["""decoder.conv_out.weight"""] UpperCamelCase_ = vae_state_dict["""decoder.conv_out.bias"""] UpperCamelCase_ = vae_state_dict["""decoder.norm_out.weight"""] UpperCamelCase_ = vae_state_dict["""decoder.norm_out.bias"""] UpperCamelCase_ = vae_state_dict["""quant_conv.weight"""] UpperCamelCase_ = vae_state_dict["""quant_conv.bias"""] UpperCamelCase_ = vae_state_dict["""post_quant_conv.weight"""] UpperCamelCase_ = vae_state_dict["""post_quant_conv.bias"""] # Retrieves the keys for the encoder down blocks only UpperCamelCase_ = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """encoder.down""" in layer} ) UpperCamelCase_ = { layer_id: [key for key in vae_state_dict if f'''down.{layer_id}''' in key] for layer_id in range(a__ ) } # Retrieves the keys for the decoder up blocks only UpperCamelCase_ = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """decoder.up""" in layer} ) UpperCamelCase_ = { layer_id: [key for key in vae_state_dict if f'''up.{layer_id}''' in key] for layer_id in range(a__ ) } for i in range(a__ ): UpperCamelCase_ = [key for key in down_blocks[i] if f'''down.{i}''' in key and f'''down.{i}.downsample''' not in key] if f'''encoder.down.{i}.downsample.conv.weight''' in vae_state_dict: UpperCamelCase_ = vae_state_dict.pop( f'''encoder.down.{i}.downsample.conv.weight''' ) UpperCamelCase_ = vae_state_dict.pop( f'''encoder.down.{i}.downsample.conv.bias''' ) UpperCamelCase_ = renew_vae_resnet_paths(a__ ) UpperCamelCase_ = {"""old""": f'''down.{i}.block''', """new""": f'''down_blocks.{i}.resnets'''} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) UpperCamelCase_ = [key for key in vae_state_dict if """encoder.mid.block""" in key] UpperCamelCase_ = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCamelCase_ = [key for key in mid_resnets if f'''encoder.mid.block_{i}''' in key] UpperCamelCase_ = renew_vae_resnet_paths(a__ ) UpperCamelCase_ = {"""old""": f'''mid.block_{i}''', """new""": f'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) UpperCamelCase_ = [key for key in vae_state_dict if """encoder.mid.attn""" in key] UpperCamelCase_ = renew_vae_attention_paths(a__ ) UpperCamelCase_ = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) conv_attn_to_linear(a__ ) for i in range(a__ ): UpperCamelCase_ = num_up_blocks - 1 - i UpperCamelCase_ = [ key for key in up_blocks[block_id] if f'''up.{block_id}''' in key and f'''up.{block_id}.upsample''' not in key ] if f'''decoder.up.{block_id}.upsample.conv.weight''' in vae_state_dict: UpperCamelCase_ = vae_state_dict[ f'''decoder.up.{block_id}.upsample.conv.weight''' ] UpperCamelCase_ = vae_state_dict[ f'''decoder.up.{block_id}.upsample.conv.bias''' ] UpperCamelCase_ = renew_vae_resnet_paths(a__ ) UpperCamelCase_ = {"""old""": f'''up.{block_id}.block''', """new""": f'''up_blocks.{i}.resnets'''} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) UpperCamelCase_ = [key for key in vae_state_dict if """decoder.mid.block""" in key] UpperCamelCase_ = 2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCamelCase_ = [key for key in mid_resnets if f'''decoder.mid.block_{i}''' in key] UpperCamelCase_ = renew_vae_resnet_paths(a__ ) UpperCamelCase_ = {"""old""": f'''mid.block_{i}''', """new""": f'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) UpperCamelCase_ = [key for key in vae_state_dict if """decoder.mid.attn""" in key] UpperCamelCase_ = renew_vae_attention_paths(a__ ) UpperCamelCase_ = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(a__ , a__ , a__ , additional_replacements=[meta_path] , config=a__ ) conv_attn_to_linear(a__ ) return new_checkpoint def lowerCamelCase__ ( a__ : str , a__ : str , ) -> List[Any]: # Only support V1 UpperCamelCase_ = requests.get( """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml""" ) UpperCamelCase_ = io.BytesIO(r.content ) UpperCamelCase_ = OmegaConf.load(a__ ) UpperCamelCase_ = 512 UpperCamelCase_ = """cuda""" if torch.cuda.is_available() else """cpu""" if checkpoint_path.endswith("""safetensors""" ): from safetensors import safe_open UpperCamelCase_ = {} with safe_open(a__ , framework="""pt""" , device="""cpu""" ) as f: for key in f.keys(): UpperCamelCase_ = f.get_tensor(a__ ) else: UpperCamelCase_ = torch.load(a__ , map_location=a__ )["""state_dict"""] # Convert the VAE model. UpperCamelCase_ = create_vae_diffusers_config(a__ , image_size=a__ ) UpperCamelCase_ = custom_convert_ldm_vae_checkpoint(a__ , a__ ) UpperCamelCase_ = AutoencoderKL(**a__ ) vae.load_state_dict(a__ ) vae.save_pretrained(a__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') _A = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
122
1
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowerCamelCase = 16 _lowerCamelCase = 32 def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Accelerator , __UpperCamelCase : int = 16 , __UpperCamelCase : str = "bert-base-cased" ) -> Union[str, Any]: UpperCAmelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) UpperCAmelCase_ = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__UpperCamelCase : str ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__UpperCamelCase : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__UpperCamelCase , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ = DataLoader( tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCAmelCase_ = DataLoader( tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Optional[Any] , __UpperCamelCase : Optional[Any] ) -> Tuple: # Initialize accelerator UpperCAmelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ = config['''lr'''] UpperCAmelCase_ = int(config['''num_epochs'''] ) UpperCAmelCase_ = int(config['''seed'''] ) UpperCAmelCase_ = int(config['''batch_size'''] ) UpperCAmelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) UpperCAmelCase_ , UpperCAmelCase_ = get_dataloaders(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase , return_dict=__UpperCamelCase ) # Instantiate optimizer UpperCAmelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ = optimizer_cls(params=model.parameters() , lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ = 1 UpperCAmelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=0 , num_training_steps=__UpperCamelCase , ) else: UpperCAmelCase_ = DummyScheduler(__UpperCamelCase , total_num_steps=__UpperCamelCase , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ = 0 # Now we train the model UpperCAmelCase_ = evaluate.load('''glue''' , '''mrpc''' ) UpperCAmelCase_ = 0 UpperCAmelCase_ = {} for epoch in range(__UpperCamelCase , __UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): UpperCAmelCase_ = model(**__UpperCamelCase ) UpperCAmelCase_ = outputs.loss UpperCAmelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCAmelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ = model(**__UpperCamelCase ) UpperCAmelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: UpperCAmelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCAmelCase_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , __UpperCamelCase ) UpperCAmelCase_ = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: UpperCAmelCase_ = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , '''all_results.json''' ) , '''w''' ) as f: json.dump(__UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE ( ) -> List[Any]: UpperCAmelCase_ = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=__UpperCamelCase , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=__UpperCamelCase , ) parser.add_argument( '''--output_dir''' , type=__UpperCamelCase , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--performance_lower_bound''' , type=__UpperCamelCase , default=__UpperCamelCase , help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''' , ) parser.add_argument( '''--num_epochs''' , type=__UpperCamelCase , default=3 , help='''Number of train epochs.''' , ) UpperCAmelCase_ = parser.parse_args() UpperCAmelCase_ = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
355
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging _lowerCamelCase = logging.get_logger(__name__) class a ( _A ): '''simple docstring''' lowerCAmelCase : str = ['input_values', 'padding_mask'] def __init__( self : Optional[Any] , __snake_case : int = 1 , __snake_case : int = 2_40_00 , __snake_case : float = 0.0 , __snake_case : float = None , __snake_case : float = None , **__snake_case : Dict , ): super().__init__(feature_size=__snake_case , sampling_rate=__snake_case , padding_value=__snake_case , **__snake_case ) UpperCAmelCase_ = chunk_length_s UpperCAmelCase_ = overlap @property def lowerCamelCase_ ( self : List[str] ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowerCamelCase_ ( self : List[str] ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self : List[str] , __snake_case : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __snake_case : Optional[Union[bool, str, PaddingStrategy]] = None , __snake_case : Optional[bool] = False , __snake_case : Optional[int] = None , __snake_case : Optional[Union[str, TensorType]] = None , __snake_case : Optional[int] = None , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with' F' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) if padding and truncation: raise ValueError('''Both padding and truncation were set. Make sure you only set one.''' ) elif padding is None: # by default let's pad the inputs UpperCAmelCase_ = True UpperCAmelCase_ = bool( isinstance(__snake_case , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCAmelCase_ = [np.asarray(__snake_case , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(__snake_case , np.ndarray ): UpperCAmelCase_ = np.asarray(__snake_case , dtype=np.floataa ) elif isinstance(__snake_case , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): UpperCAmelCase_ = raw_audio.astype(np.floataa ) # always return batch if not is_batched: UpperCAmelCase_ = [np.asarray(__snake_case ).T] # verify inputs are valid for idx, example in enumerate(__snake_case ): if example.ndim > 2: raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' ) UpperCAmelCase_ = None UpperCAmelCase_ = BatchFeature({'''input_values''': raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: UpperCAmelCase_ = min(array.shape[0] for array in raw_audio ) UpperCAmelCase_ = int(np.floor(max_length / self.chunk_stride ) ) UpperCAmelCase_ = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: UpperCAmelCase_ = max(array.shape[0] for array in raw_audio ) UpperCAmelCase_ = int(np.ceil(max_length / self.chunk_stride ) ) UpperCAmelCase_ = (nb_step - 1) * self.chunk_stride + self.chunk_length UpperCAmelCase_ = '''max_length''' else: UpperCAmelCase_ = input_values # normal padding on batch if padded_inputs is None: UpperCAmelCase_ = self.pad( __snake_case , max_length=__snake_case , truncation=__snake_case , padding=__snake_case , return_attention_mask=__snake_case , ) if padding: UpperCAmelCase_ = padded_inputs.pop('''attention_mask''' ) UpperCAmelCase_ = [] for example in padded_inputs.pop('''input_values''' ): if self.feature_size == 1: UpperCAmelCase_ = example[..., None] input_values.append(example.T ) UpperCAmelCase_ = input_values if return_tensors is not None: UpperCAmelCase_ = padded_inputs.convert_to_tensors(__snake_case ) return padded_inputs
177
0
__UpperCAmelCase = 8.3_1_4_4_5_9_8 def lowercase__ ( __snake_case : float , __snake_case : float ): '''simple docstring''' if temperature < 0: raise Exception('Temperature cannot be less than 0 K' ) if molar_mass <= 0: raise Exception('Molar mass cannot be less than or equal to 0 kg/mol' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example __UpperCAmelCase = 300 __UpperCAmelCase = 28 __UpperCAmelCase = rms_speed_of_molecule(temperature, molar_mass) print(F'Vrms of Nitrogen gas at 300 K is {vrms} m/s')
29
from __future__ import annotations lowerCamelCase__ : Optional[int] = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] lowerCamelCase__ : List[Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def UpperCAmelCase_ ( __UpperCAmelCase : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = len(__UpperCAmelCase ) for i in range(__UpperCAmelCase ): SCREAMING_SNAKE_CASE_ = -1 for j in range(i + 1 , __UpperCAmelCase ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE_ = arr[j] break result.append(__UpperCAmelCase ) return result def UpperCAmelCase_ ( __UpperCAmelCase : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = [] for i, outer in enumerate(__UpperCAmelCase ): SCREAMING_SNAKE_CASE_ = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE_ = inner break result.append(__UpperCAmelCase ) return result def UpperCAmelCase_ ( __UpperCAmelCase : list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = len(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [-1] * arr_size for index in reversed(range(__UpperCAmelCase ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE_ = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) lowerCamelCase__ : List[str] = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
225
0
def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase) -> int: a = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): a = n - k # Calculate C(n,k) for i in range(__UpperCamelCase): result *= n - i result //= i + 1 return result def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> int: return binomial_coefficient(2 * node_count , __UpperCamelCase) // (node_count + 1) def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> int: if n < 0: raise ValueError("factorial() not defined for negative values") a = 1 for i in range(1 , n + 1): result *= i return result def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> int: return catalan_number(__UpperCamelCase) * factorial(__UpperCamelCase) if __name__ == "__main__": lowercase__ : Optional[int] = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( F'Given {node_count} nodes, there are {binary_tree_count(node_count)} ' F'binary trees and {catalan_number(node_count)} binary search trees.' )
353
def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> int: return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> bool: a = 0 a = number while duplicate > 0: a , a = divmod(__UpperCamelCase , 10) fact_sum += factorial(__UpperCamelCase) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") lowercase__ : str = int(input("Enter number: ").strip()) print( F'{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.' )
180
0
"""simple docstring""" import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class _UpperCAmelCase ( __snake_case ): '''simple docstring''' lowerCamelCase__ =['image_processor', 'tokenizer'] lowerCamelCase__ ='BlipImageProcessor' lowerCamelCase__ ='AutoTokenizer' def __init__(self , a_ , a_ , a_ ): '''simple docstring''' super().__init__(a_ , a_ ) # add QFormer tokenizer __snake_case : Optional[Any] = qformer_tokenizer def __call__(self , a_ = None , a_ = None , a_ = True , a_ = False , a_ = None , a_ = None , a_ = 0 , a_ = None , a_ = None , a_ = False , a_ = False , a_ = False , a_ = False , a_ = False , a_ = True , a_ = None , **a_ , ): '''simple docstring''' if images is None and text is None: raise ValueError('''You have to specify at least images or text.''' ) __snake_case : Any = BatchFeature() if text is not None: __snake_case : str = self.tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) encoding.update(a_ ) __snake_case : Dict = self.qformer_tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) __snake_case : List[str] = qformer_text_encoding.pop('''input_ids''' ) __snake_case : Union[str, Any] = qformer_text_encoding.pop('''attention_mask''' ) if images is not None: __snake_case : List[Any] = self.image_processor(a_ , return_tensors=a_ ) encoding.update(a_ ) return encoding def SCREAMING_SNAKE_CASE (self , *a_ , **a_ ): '''simple docstring''' return self.tokenizer.batch_decode(*a_ , **a_ ) def SCREAMING_SNAKE_CASE (self , *a_ , **a_ ): '''simple docstring''' return self.tokenizer.decode(*a_ , **a_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Tuple = self.tokenizer.model_input_names __snake_case : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def SCREAMING_SNAKE_CASE (self , a_ , **a_ ): '''simple docstring''' if os.path.isfile(a_ ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(a_ , exist_ok=a_ ) __snake_case : str = os.path.join(a_ , '''qformer_tokenizer''' ) self.qformer_tokenizer.save_pretrained(a_ ) return super().save_pretrained(a_ , **a_ ) @classmethod def SCREAMING_SNAKE_CASE (cls , a_ , **a_ ): '''simple docstring''' __snake_case : Any = AutoTokenizer.from_pretrained(a_ , subfolder='''qformer_tokenizer''' ) __snake_case : str = cls._get_arguments_from_pretrained(a_ , **a_ ) args.append(a_ ) return cls(*a_ )
102
'''simple docstring''' def _A ( lowercase__ = 1000000 ): lowercase__ = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
164
0
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class _UpperCAmelCase ( __snake_case, __snake_case, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =AutoencoderKL lowerCamelCase__ ='sample' lowerCamelCase__ =1E-2 @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : int = 4 __snake_case : Optional[Any] = 3 __snake_case : Dict = (32, 32) __snake_case : Any = floats_tensor((batch_size, num_channels) + sizes ).to(a_ ) return {"sample": image} @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return (3, 32, 32) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return (3, 32, 32) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } __snake_case : str = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' pass @unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : Dict = self.model_class(**a_ ) model.to(a_ ) assert not model.is_gradient_checkpointing and model.training __snake_case : Tuple = model(**a_ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __snake_case : List[str] = torch.randn_like(a_ ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**a_ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(a_ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : List[str] = model_a(**a_ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __snake_case : Dict = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Dict = dict(model.named_parameters() ) __snake_case : int = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case , __snake_case : int = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(a_ ) __snake_case : Any = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ) __snake_case : Tuple = model.to(a_ ) model.eval() if torch_device == "mps": __snake_case : str = torch.manual_seed(0 ) else: __snake_case : Optional[Any] = torch.Generator(device=a_ ).manual_seed(0 ) __snake_case : List[Any] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : str = image.to(a_ ) with torch.no_grad(): __snake_case : Tuple = model(a_ , sample_posterior=a_ , generator=a_ ).sample __snake_case : Optional[int] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __snake_case : List[str] = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __snake_case : Any = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: __snake_case : str = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(a_ , a_ , rtol=1E-2 ) ) @slow class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' return f"""gaussian_noise_s={seed}_shape={'_'.join([str(a_ ) for s in shape] )}.npy""" def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE (self , a_=0 , a_=(4, 3, 5_12, 5_12) , a_=False ): '''simple docstring''' __snake_case : Any = torch.floataa if fpaa else torch.floataa __snake_case : Any = torch.from_numpy(load_hf_numpy(self.get_file_format(a_ , a_ ) ) ).to(a_ ).to(a_ ) return image def SCREAMING_SNAKE_CASE (self , a_="CompVis/stable-diffusion-v1-4" , a_=False ): '''simple docstring''' __snake_case : List[Any] = '''fp16''' if fpaa else None __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = AutoencoderKL.from_pretrained( a_ , subfolder='''vae''' , torch_dtype=a_ , revision=a_ , ) model.to(a_ ).eval() return model def SCREAMING_SNAKE_CASE (self , a_=0 ): '''simple docstring''' if torch_device == "mps": return torch.manual_seed(a_ ) return torch.Generator(device=a_ ).manual_seed(a_ ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ ): '''simple docstring''' __snake_case : int = self.get_sd_vae_model() __snake_case : Dict = self.get_sd_image(a_ ) __snake_case : List[Any] = self.get_generator(a_ ) with torch.no_grad(): __snake_case : Optional[int] = model(a_ , generator=a_ , sample_posterior=a_ ).sample assert sample.shape == image.shape __snake_case : int = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : Optional[int] = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(a_ , a_ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : List[str] = self.get_sd_vae_model(fpaa=a_ ) __snake_case : List[Any] = self.get_sd_image(a_ , fpaa=a_ ) __snake_case : int = self.get_generator(a_ ) with torch.no_grad(): __snake_case : str = model(a_ , generator=a_ , sample_posterior=a_ ).sample assert sample.shape == image.shape __snake_case : Optional[int] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Tuple = torch.tensor(a_ ) assert torch_all_close(a_ , a_ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ ): '''simple docstring''' __snake_case : Tuple = self.get_sd_vae_model() __snake_case : Optional[Any] = self.get_sd_image(a_ ) with torch.no_grad(): __snake_case : List[Any] = model(a_ ).sample assert sample.shape == image.shape __snake_case : Dict = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : Any = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(a_ , a_ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : int = self.get_sd_vae_model() __snake_case : Tuple = self.get_sd_image(a_ , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(a_ ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] __snake_case : Dict = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Any = torch.tensor(a_ ) assert torch_all_close(a_ , a_ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Any = self.get_sd_vae_model(fpaa=a_ ) __snake_case : Union[str, Any] = self.get_sd_image(a_ , shape=(3, 4, 64, 64) , fpaa=a_ ) with torch.no_grad(): __snake_case : Optional[int] = model.decode(a_ ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Dict = torch.tensor(a_ ) assert torch_all_close(a_ , a_ , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : Any = self.get_sd_vae_model(fpaa=a_ ) __snake_case : Any = self.get_sd_image(a_ , shape=(3, 4, 64, 64) , fpaa=a_ ) with torch.no_grad(): __snake_case : Optional[int] = model.decode(a_ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(a_ ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] assert torch_all_close(a_ , a_ , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : Optional[int] = self.get_sd_vae_model() __snake_case : str = self.get_sd_image(a_ , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : Optional[Any] = model.decode(a_ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Optional[Any] = model.decode(a_ ).sample assert list(sample.shape ) == [3, 3, 5_12, 5_12] assert torch_all_close(a_ , a_ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Tuple = self.get_sd_vae_model() __snake_case : Optional[int] = self.get_sd_image(a_ ) __snake_case : List[str] = self.get_generator(a_ ) with torch.no_grad(): __snake_case : List[str] = model.encode(a_ ).latent_dist __snake_case : int = dist.sample(generator=a_ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : Optional[Any] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Union[str, Any] = torch.tensor(a_ ) __snake_case : str = 3E-3 if torch_device != '''mps''' else 1E-2 assert torch_all_close(a_ , a_ , atol=a_ )
24
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : int = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE : List[Any] = { """vocab_file""": { """facebook/mbart-large-en-ro""": ( """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model""" ), """facebook/mbart-large-cc25""": ( """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """facebook/mbart-large-en-ro""": """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json""", """facebook/mbart-large-cc25""": """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE : Tuple = { """facebook/mbart-large-en-ro""": 1024, """facebook/mbart-large-cc25""": 1024, } # fmt: off SCREAMING_SNAKE_CASE : List[Any] = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""] class _UpperCAmelCase ( __snake_case ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =['input_ids', 'attention_mask'] lowerCamelCase__ =MBartTokenizer lowerCamelCase__ =[] lowerCamelCase__ =[] def __init__(self , a_=None , a_=None , a_="<s>" , a_="</s>" , a_="</s>" , a_="<s>" , a_="<unk>" , a_="<pad>" , a_="<mask>" , a_=None , a_=None , a_=None , **a_ , ): '''simple docstring''' __snake_case : Optional[int] = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token super().__init__( vocab_file=a_ , tokenizer_file=a_ , bos_token=a_ , eos_token=a_ , sep_token=a_ , cls_token=a_ , unk_token=a_ , pad_token=a_ , mask_token=a_ , src_lang=a_ , tgt_lang=a_ , additional_special_tokens=a_ , **a_ , ) __snake_case : Tuple = vocab_file __snake_case : Optional[Any] = False if not self.vocab_file else True __snake_case : Dict = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) __snake_case : Optional[int] = { lang_code: self.convert_tokens_to_ids(a_ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __snake_case : List[Any] = src_lang if src_lang is not None else '''en_XX''' __snake_case : Any = self.convert_tokens_to_ids(self._src_lang ) __snake_case : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self._src_lang @src_lang.setter def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' __snake_case : Tuple = [self.sep_token_id] __snake_case : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_ , **a_ ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) __snake_case : Optional[int] = src_lang __snake_case : Tuple = self(a_ , add_special_tokens=a_ , return_tensors=a_ , **a_ ) __snake_case : Union[str, Any] = self.convert_tokens_to_ids(a_ ) __snake_case : int = tgt_lang_id return inputs def SCREAMING_SNAKE_CASE (self , a_ , a_ = "en_XX" , a_ = None , a_ = "ro_RO" , **a_ , ): '''simple docstring''' __snake_case : int = src_lang __snake_case : List[Any] = tgt_lang return super().prepare_seqaseq_batch(a_ , a_ , **a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : int = self.convert_tokens_to_ids(a_ ) __snake_case : List[Any] = [] __snake_case : Any = [self.eos_token_id, self.cur_lang_code] __snake_case : List[str] = self.convert_ids_to_tokens(self.prefix_tokens ) __snake_case : Dict = self.convert_ids_to_tokens(self.suffix_tokens ) __snake_case : Any = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : int = self.convert_tokens_to_ids(a_ ) __snake_case : Optional[Any] = [] __snake_case : Dict = [self.eos_token_id, self.cur_lang_code] __snake_case : str = self.convert_ids_to_tokens(self.prefix_tokens ) __snake_case : Any = self.convert_ids_to_tokens(self.suffix_tokens ) __snake_case : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(a_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return __snake_case : Optional[Any] = os.path.join( a_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) return (out_vocab_file,)
24
1
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ): """simple docstring""" # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowerCamelCase__ : Dict =ksize + 1 lowerCamelCase__ : Any =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(__lowerCamelCase ): for x in range(__lowerCamelCase ): # distance from center lowerCamelCase__ : Any =x - ksize // 2 lowerCamelCase__ : Tuple =y - ksize // 2 # degree to radiant lowerCamelCase__ : int =theta / 180 * np.pi lowerCamelCase__ : int =np.cos(_theta ) lowerCamelCase__ : Tuple =np.sin(_theta ) # get kernel x lowerCamelCase__ : List[Any] =cos_theta * px + sin_theta * py # get kernel y lowerCamelCase__ : Any =-sin_theta * px + cos_theta * py # fill kernel lowerCamelCase__ : List[Any] =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image _lowercase : int = imread("../image_data/lena.jpg") # turn image in gray scale value _lowercase : Dict = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges _lowercase : Dict = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: _lowercase : Dict = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) _lowercase : List[Any] = out / out.max() * 2_5_5 _lowercase : str = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
238
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=True , __lowerCamelCase : Dict="pt" ): """simple docstring""" lowerCamelCase__ : str ={'''add_prefix_space''': True} if isinstance(__lowerCamelCase , __lowerCamelCase ) and not line.startswith(''' ''' ) else {} lowerCamelCase__ : int =padding_side return tokenizer( [line] , max_length=__lowerCamelCase , padding='''max_length''' if pad_to_max_length else None , truncation=__lowerCamelCase , return_tensors=__lowerCamelCase , add_special_tokens=__lowerCamelCase , **__lowerCamelCase , ) def snake_case__ ( __lowerCamelCase : str , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int]=None , ): """simple docstring""" lowerCamelCase__ : Any =input_ids.ne(__lowerCamelCase ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : str, lowerCamelCase : Union[str, Any], lowerCamelCase : Dict, lowerCamelCase : Union[str, Any], lowerCamelCase : Dict, lowerCamelCase : str="train", lowerCamelCase : List[Any]=None, lowerCamelCase : Tuple=None, lowerCamelCase : List[str]=None, lowerCamelCase : int="", )-> List[Any]: super().__init__() lowerCamelCase__ : Tuple =Path(lowerCamelCase ).joinpath(type_path + '''.source''' ) lowerCamelCase__ : str =Path(lowerCamelCase ).joinpath(type_path + '''.target''' ) lowerCamelCase__ : Dict =self.get_char_lens(self.src_file ) lowerCamelCase__ : Tuple =max_source_length lowerCamelCase__ : Optional[int] =max_target_length assert min(self.src_lens ) > 0, F'''found empty line in {self.src_file}''' lowerCamelCase__ : Dict =tokenizer lowerCamelCase__ : List[str] =prefix if n_obs is not None: lowerCamelCase__ : int =self.src_lens[:n_obs] lowerCamelCase__ : Dict =src_lang lowerCamelCase__ : Tuple =tgt_lang def __len__( self : Dict )-> Optional[int]: return len(self.src_lens ) def __getitem__( self : List[str], lowerCamelCase : Optional[int] )-> Dict[str, torch.Tensor]: lowerCamelCase__ : List[Any] =index + 1 # linecache starts at 1 lowerCamelCase__ : Optional[int] =self.prefix + linecache.getline(str(self.src_file ), lowerCamelCase ).rstrip('''\n''' ) lowerCamelCase__ : Optional[Any] =linecache.getline(str(self.tgt_file ), lowerCamelCase ).rstrip('''\n''' ) assert source_line, F'''empty source line for index {index}''' assert tgt_line, F'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer, lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowerCamelCase__ : Optional[int] =( self.tokenizer.question_encoder if isinstance(self.tokenizer, lowerCamelCase ) else self.tokenizer ) lowerCamelCase__ : Tuple =self.tokenizer.generator if isinstance(self.tokenizer, lowerCamelCase ) else self.tokenizer lowerCamelCase__ : Optional[int] =encode_line(lowerCamelCase, lowerCamelCase, self.max_source_length, '''right''' ) lowerCamelCase__ : str =encode_line(lowerCamelCase, lowerCamelCase, self.max_target_length, '''right''' ) lowerCamelCase__ : str =source_inputs['''input_ids'''].squeeze() lowerCamelCase__ : str =target_inputs['''input_ids'''].squeeze() lowerCamelCase__ : Union[str, Any] =source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def snake_case ( lowerCamelCase : Union[str, Any] )-> Optional[int]: return [len(lowerCamelCase ) for x in Path(lowerCamelCase ).open().readlines()] def snake_case ( self : str, lowerCamelCase : str )-> Dict[str, torch.Tensor]: lowerCamelCase__ : List[Any] =torch.stack([x['''input_ids'''] for x in batch] ) lowerCamelCase__ : int =torch.stack([x['''attention_mask'''] for x in batch] ) lowerCamelCase__ : Union[str, Any] =torch.stack([x['''decoder_input_ids'''] for x in batch] ) lowerCamelCase__ : str =( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer, lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCamelCase__ : List[str] =( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer, lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCamelCase__ : Optional[int] =trim_batch(lowerCamelCase, lowerCamelCase ) lowerCamelCase__ , lowerCamelCase__ : Any =trim_batch(lowerCamelCase, lowerCamelCase, attention_mask=lowerCamelCase ) lowerCamelCase__ : List[str] ={ '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowercase : Any = getLogger(__name__) def snake_case__ ( __lowerCamelCase : List[List] ): """simple docstring""" return list(itertools.chain.from_iterable(__lowerCamelCase ) ) def snake_case__ ( __lowerCamelCase : str ): """simple docstring""" lowerCamelCase__ : Dict =get_git_info() save_json(__lowerCamelCase , os.path.join(__lowerCamelCase , '''git_log.json''' ) ) def snake_case__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict=4 , **__lowerCamelCase : int ): """simple docstring""" with open(__lowerCamelCase , '''w''' ) as f: json.dump(__lowerCamelCase , __lowerCamelCase , indent=__lowerCamelCase , **__lowerCamelCase ) def snake_case__ ( __lowerCamelCase : List[Any] ): """simple docstring""" with open(__lowerCamelCase ) as f: return json.load(__lowerCamelCase ) def snake_case__ ( ): """simple docstring""" lowerCamelCase__ : List[Any] =git.Repo(search_parent_directories=__lowerCamelCase ) lowerCamelCase__ : Union[str, Any] ={ '''repo_id''': str(__lowerCamelCase ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case__ ( __lowerCamelCase : Callable , __lowerCamelCase : Iterable ): """simple docstring""" return list(map(__lowerCamelCase , __lowerCamelCase ) ) def snake_case__ ( __lowerCamelCase : Any , __lowerCamelCase : List[Any] ): """simple docstring""" with open(__lowerCamelCase , '''wb''' ) as f: return pickle.dump(__lowerCamelCase , __lowerCamelCase ) def snake_case__ ( __lowerCamelCase : str ): """simple docstring""" def remove_articles(__lowerCamelCase : List[Any] ): return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , __lowerCamelCase ) def white_space_fix(__lowerCamelCase : Any ): return " ".join(text.split() ) def remove_punc(__lowerCamelCase : Optional[Any] ): lowerCamelCase__ : Tuple =set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCamelCase : Any ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCamelCase ) ) ) ) def snake_case__ ( __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ): """simple docstring""" lowerCamelCase__ : List[str] =normalize_answer(__lowerCamelCase ).split() lowerCamelCase__ : List[str] =normalize_answer(__lowerCamelCase ).split() lowerCamelCase__ : Optional[int] =Counter(__lowerCamelCase ) & Counter(__lowerCamelCase ) lowerCamelCase__ : Union[str, Any] =sum(common.values() ) if num_same == 0: return 0 lowerCamelCase__ : Dict =1.0 * num_same / len(__lowerCamelCase ) lowerCamelCase__ : List[str] =1.0 * num_same / len(__lowerCamelCase ) lowerCamelCase__ : Union[str, Any] =(2 * precision * recall) / (precision + recall) return fa def snake_case__ ( __lowerCamelCase : Dict , __lowerCamelCase : int ): """simple docstring""" return normalize_answer(__lowerCamelCase ) == normalize_answer(__lowerCamelCase ) def snake_case__ ( __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ): """simple docstring""" assert len(__lowerCamelCase ) == len(__lowerCamelCase ) lowerCamelCase__ : Any =0 for hypo, pred in zip(__lowerCamelCase , __lowerCamelCase ): em += exact_match_score(__lowerCamelCase , __lowerCamelCase ) if len(__lowerCamelCase ) > 0: em /= len(__lowerCamelCase ) return {"em": em} def snake_case__ ( __lowerCamelCase : List[str] ): """simple docstring""" return model_prefix.startswith('''rag''' ) def snake_case__ ( __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : str ): """simple docstring""" lowerCamelCase__ : Any ={p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowerCamelCase__ : Optional[int] ='''dropout_rate''' for p in extra_params: if getattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if not hasattr(__lowerCamelCase , __lowerCamelCase ) and not hasattr(__lowerCamelCase , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(__lowerCamelCase ) ) delattr(__lowerCamelCase , __lowerCamelCase ) continue lowerCamelCase__ : List[Any] =p if hasattr(__lowerCamelCase , __lowerCamelCase ) else equivalent_param[p] setattr(__lowerCamelCase , __lowerCamelCase , getattr(__lowerCamelCase , __lowerCamelCase ) ) delattr(__lowerCamelCase , __lowerCamelCase ) return hparams, config
238
1
"""simple docstring""" import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCamelCase: Dict = logging.get_logger(__name__) _UpperCamelCase: Optional[int] = { 'nvidia/segformer-b0-finetuned-ade-512-512': ( 'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class a__ ( SCREAMING_SNAKE_CASE__ ): _lowerCamelCase = 'segformer' def __init__( self : int, lowerCAmelCase : Tuple=3, lowerCAmelCase : Union[str, Any]=4, lowerCAmelCase : Optional[int]=[2, 2, 2, 2], lowerCAmelCase : Any=[8, 4, 2, 1], lowerCAmelCase : Optional[int]=[32, 64, 160, 256], lowerCAmelCase : Optional[int]=[7, 3, 3, 3], lowerCAmelCase : List[str]=[4, 2, 2, 2], lowerCAmelCase : str=[1, 2, 5, 8], lowerCAmelCase : Union[str, Any]=[4, 4, 4, 4], lowerCAmelCase : Any="gelu", lowerCAmelCase : List[str]=0.0, lowerCAmelCase : Tuple=0.0, lowerCAmelCase : str=0.1, lowerCAmelCase : Union[str, Any]=0.02, lowerCAmelCase : int=0.1, lowerCAmelCase : Tuple=1e-6, lowerCAmelCase : List[Any]=256, lowerCAmelCase : List[str]=255, **lowerCAmelCase : Dict, ) -> Union[str, Any]: super().__init__(**lowerCAmelCase ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.', lowerCAmelCase, ) lowercase : Union[str, Any] = num_channels lowercase : Optional[Any] = num_encoder_blocks lowercase : Optional[Any] = depths lowercase : Any = sr_ratios lowercase : List[str] = hidden_sizes lowercase : List[Any] = patch_sizes lowercase : Any = strides lowercase : List[Any] = mlp_ratios lowercase : Any = num_attention_heads lowercase : Union[str, Any] = hidden_act lowercase : Optional[Any] = hidden_dropout_prob lowercase : Union[str, Any] = attention_probs_dropout_prob lowercase : str = classifier_dropout_prob lowercase : List[str] = initializer_range lowercase : Tuple = drop_path_rate lowercase : Dict = layer_norm_eps lowercase : List[Any] = decoder_hidden_size lowercase : Optional[Any] = kwargs.get('reshape_last_stage', lowerCAmelCase ) lowercase : Tuple = semantic_loss_ignore_index class a__ ( SCREAMING_SNAKE_CASE__ ): _lowerCamelCase = version.parse('1.11' ) @property def lowercase ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def lowercase ( self : List[str] ) -> float: return 1e-4 @property def lowercase ( self : Any ) -> int: return 12
53
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _UpperCamelCase: List[str] = logging.get_logger(__name__) _UpperCamelCase: List[str] = {'tokenizer_file': 'tokenizer.json'} _UpperCamelCase: str = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class a__ ( SCREAMING_SNAKE_CASE__ ): _lowerCamelCase = VOCAB_FILES_NAMES _lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase = ['input_ids', 'attention_mask'] _lowerCamelCase = None def __init__( self : Tuple, lowerCAmelCase : Tuple=None, lowerCAmelCase : Optional[Any]=None, lowerCAmelCase : str=None, lowerCAmelCase : Union[str, Any]="<unk>", lowerCAmelCase : Any="<s>", lowerCAmelCase : str="</s>", lowerCAmelCase : Tuple="<pad>", lowerCAmelCase : Dict=False, lowerCAmelCase : Union[str, Any]=False, **lowerCAmelCase : Optional[Any], ) -> str: super().__init__( lowerCAmelCase, lowerCAmelCase, tokenizer_file=lowerCAmelCase, unk_token=lowerCAmelCase, bos_token=lowerCAmelCase, eos_token=lowerCAmelCase, pad_token=lowerCAmelCase, add_prefix_space=lowerCAmelCase, clean_up_tokenization_spaces=lowerCAmelCase, **lowerCAmelCase, ) lowercase : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space', lowerCAmelCase ) != add_prefix_space: lowercase : Dict = getattr(lowerCAmelCase, pre_tok_state.pop('type' ) ) lowercase : Optional[Any] = add_prefix_space lowercase : List[str] = pre_tok_class(**lowerCAmelCase ) lowercase : List[str] = add_prefix_space def lowercase ( self : Dict, *lowerCAmelCase : Tuple, **lowerCAmelCase : List[Any] ) -> BatchEncoding: lowercase : str = kwargs.get('is_split_into_words', lowerCAmelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' ' pretokenized inputs.' ) return super()._batch_encode_plus(*lowerCAmelCase, **lowerCAmelCase ) def lowercase ( self : List[Any], *lowerCAmelCase : Dict, **lowerCAmelCase : Dict ) -> BatchEncoding: lowercase : List[str] = kwargs.get('is_split_into_words', lowerCAmelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' ' pretokenized inputs.' ) return super()._encode_plus(*lowerCAmelCase, **lowerCAmelCase ) def lowercase ( self : Optional[int], lowerCAmelCase : str, lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: lowercase : Optional[Any] = self._tokenizer.model.save(lowerCAmelCase, name=lowerCAmelCase ) return tuple(lowerCAmelCase ) def lowercase ( self : Tuple, lowerCAmelCase : "Conversation" ) -> List[int]: lowercase : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCAmelCase, add_special_tokens=lowerCAmelCase ) + [self.eos_token_id] ) if len(lowerCAmelCase ) > self.model_max_length: lowercase : Optional[Any] = input_ids[-self.model_max_length :] return input_ids
53
1
'''simple docstring''' import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class A_ ( lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : str = CanineTokenizer _lowerCamelCase : Tuple = False def lowercase ( self : List[Any] ): super().setUp() _UpperCAmelCase = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase ( self : List[str] ): return CanineTokenizer.from_pretrained("google/canine-s" ) def lowercase ( self : Union[str, Any] , **snake_case_ : List[Any] ): _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname , **snake_case_ ) _UpperCAmelCase = 1_0_2_4 return tokenizer @require_torch def lowercase ( self : List[str] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = ["Life is like a box of chocolates.", "You never know what you're gonna get."] # fmt: off _UpperCAmelCase = [5_7_3_4_4, 7_6, 1_0_5, 1_0_2, 1_0_1, 3_2, 1_0_5, 1_1_5, 3_2, 1_0_8, 1_0_5, 1_0_7, 1_0_1, 3_2, 9_7, 3_2, 9_8, 1_1_1, 1_2_0, 3_2, 1_1_1, 1_0_2, 3_2, 9_9, 1_0_4, 1_1_1, 9_9, 1_1_1, 1_0_8, 9_7, 1_1_6, 1_0_1, 1_1_5, 4_6, 5_7_3_4_5, 0, 0, 0, 0] # fmt: on _UpperCAmelCase = tokenizer(snake_case_ , padding=snake_case_ , return_tensors="pt" ) self.assertIsInstance(snake_case_ , snake_case_ ) _UpperCAmelCase = list(batch.input_ids.numpy()[0] ) self.assertListEqual(snake_case_ , snake_case_ ) self.assertEqual((2, 3_9) , batch.input_ids.shape ) self.assertEqual((2, 3_9) , batch.attention_mask.shape ) @require_torch def lowercase ( self : List[Any] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."] _UpperCAmelCase = tokenizer(snake_case_ , padding=snake_case_ , return_tensors="pt" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("input_ids" , snake_case_ ) self.assertIn("attention_mask" , snake_case_ ) self.assertIn("token_type_ids" , snake_case_ ) @require_torch def lowercase ( self : Optional[int] ): _UpperCAmelCase = self.canine_tokenizer _UpperCAmelCase = [ "What's the weater?", "It's about 25 degrees.", ] _UpperCAmelCase = tokenizer( text_target=snake_case_ , max_length=3_2 , padding="max_length" , truncation=snake_case_ , return_tensors="pt" ) self.assertEqual(3_2 , targets["input_ids"].shape[1] ) def lowercase ( self : Union[str, Any] ): # safety check on max_len default value so we are sure the test works _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = " He is very happy, UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) tokenizer.save_pretrained(snake_case_ ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ ) _UpperCAmelCase = after_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) shutil.rmtree(snake_case_ ) _UpperCAmelCase = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = " He is very happy, UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: _UpperCAmelCase = chr(0Xe0_07 ) additional_special_tokens.append(snake_case_ ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) tokenizer.save_pretrained(snake_case_ ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ ) _UpperCAmelCase = after_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) self.assertIn(snake_case_ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(snake_case_ , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(snake_case_ ) def lowercase ( self : int ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase , _UpperCAmelCase = self.get_clean_sequence(snake_case_ ) # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_05 _UpperCAmelCase = chr(snake_case_ ) tokenizer.add_special_tokens({"cls_token": special_token} ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertEqual(len(snake_case_ ) , 1 ) _UpperCAmelCase = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertEqual(snake_case_ , input_encoded + special_token_id ) _UpperCAmelCase = tokenizer.decode(snake_case_ , skip_special_tokens=snake_case_ ) self.assertTrue(special_token not in decoded ) def lowercase ( self : int ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = chr(0Xe0_05 ) _UpperCAmelCase = chr(0Xe0_06 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=snake_case_ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]} ) _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) self.assertEqual(len(snake_case_ ) , 1 ) self.assertEqual(len(snake_case_ ) , 1 ) self.assertEqual(token_a[0] , snake_case_ ) self.assertEqual(token_a[0] , snake_case_ ) @require_tokenizers def lowercase ( self : Any ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) _UpperCAmelCase = AddedToken(snake_case_ , lstrip=snake_case_ ) tokenizer.add_special_tokens({"additional_special_tokens": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(snake_case_ ) tokenizer.from_pretrained(snake_case_ ) def lowercase ( self : List[Any] ): _UpperCAmelCase = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(snake_case_ ) with open(os.path.join(snake_case_ , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: _UpperCAmelCase = json.load(snake_case_ ) with open(os.path.join(snake_case_ , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: _UpperCAmelCase = json.load(snake_case_ ) # a special token for Canine can be defined as follows: _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) _UpperCAmelCase = [new_token_a] _UpperCAmelCase = [new_token_a] with open(os.path.join(snake_case_ , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(snake_case_ , snake_case_ ) with open(os.path.join(snake_case_ , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(snake_case_ , snake_case_ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _UpperCAmelCase = tokenizer_class.from_pretrained(snake_case_ , extra_ids=0 ) self.assertIn(snake_case_ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) _UpperCAmelCase = 0Xe0_07 _UpperCAmelCase = chr(snake_case_ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _UpperCAmelCase = [AddedToken(snake_case_ , lstrip=snake_case_ )] _UpperCAmelCase = tokenizer_class.from_pretrained( snake_case_ , additional_special_tokens=snake_case_ , extra_ids=0 ) self.assertIn(snake_case_ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def lowercase ( self : Tuple ): _UpperCAmelCase = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = "hello world" if self.space_between_special_tokens: _UpperCAmelCase = "[CLS] hello world [SEP]" else: _UpperCAmelCase = input _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.decode(snake_case_ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(snake_case_ , [output, output.lower()] ) def lowercase ( self : str ): _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] _UpperCAmelCase = "a" _UpperCAmelCase = ord(snake_case_ ) for attr in attributes_list: setattr(snake_case_ , attr + "_id" , snake_case_ ) self.assertEqual(getattr(snake_case_ , snake_case_ ) , snake_case_ ) self.assertEqual(getattr(snake_case_ , attr + "_id" ) , snake_case_ ) setattr(snake_case_ , attr + "_id" , snake_case_ ) self.assertEqual(getattr(snake_case_ , snake_case_ ) , snake_case_ ) self.assertEqual(getattr(snake_case_ , attr + "_id" ) , snake_case_ ) setattr(snake_case_ , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens_ids" ) , [] ) _UpperCAmelCase = 0Xe0_06 _UpperCAmelCase = chr(snake_case_ ) setattr(snake_case_ , "additional_special_tokens_ids" , [additional_special_token_id] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens" ) , [additional_special_token] ) self.assertListEqual(getattr(snake_case_ , "additional_special_tokens_ids" ) , [additional_special_token_id] ) def lowercase ( self : Any ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : Union[str, Any] ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : List[Any] ): pass def lowercase ( self : int ): pass def lowercase ( self : int ): pass def lowercase ( self : Optional[Any] ): pass
22
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml _UpperCAmelCase : Optional[Any] =NewType("""DataClass""", Any) _UpperCAmelCase : Dict =NewType("""DataClassType""", Any) def lowerCAmelCase ( lowerCAmelCase_ )-> Tuple: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" ) def lowerCAmelCase ( lowerCAmelCase_ )-> Callable[[str], Any]: lowerCAmelCase_ : str = {str(lowerCAmelCase_ ): choice for choice in choices} return lambda lowerCAmelCase_ : str_to_choice.get(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCAmelCase ( *, lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = dataclasses.MISSING , lowerCAmelCase_ = dataclasses.MISSING , lowerCAmelCase_ = None , **lowerCAmelCase_ , )-> dataclasses.Field: if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls lowerCAmelCase_ : Dict = {} if aliases is not None: lowerCAmelCase_ : str = aliases if help is not None: lowerCAmelCase_ : Tuple = help return dataclasses.field(metadata=lowerCAmelCase_ , default=lowerCAmelCase_ , default_factory=lowerCAmelCase_ , **lowerCAmelCase_ ) class snake_case__( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Iterable[DataClassType] def __init__( self , __lowercase , **__lowercase ) -> List[str]: # To make the default appear when using --help if "formatter_class" not in kwargs: lowerCAmelCase_ : Optional[int] = ArgumentDefaultsHelpFormatter super().__init__(**__lowercase ) if dataclasses.is_dataclass(__lowercase ): lowerCAmelCase_ : Union[str, Any] = [dataclass_types] lowerCAmelCase_ : List[Any] = list(__lowercase ) for dtype in self.dataclass_types: self._add_dataclass_arguments(__lowercase ) @staticmethod def lowercase_ ( __lowercase , __lowercase ) -> Union[str, Any]: lowerCAmelCase_ : Optional[Any] = f"""--{field.name}""" lowerCAmelCase_ : Tuple = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , __lowercase ): raise RuntimeError( '''Unresolved type detected, which should have been done with the help of ''' '''`typing.get_type_hints` method by default''' ) lowerCAmelCase_ : List[str] = kwargs.pop('''aliases''' , [] ) if isinstance(__lowercase , __lowercase ): lowerCAmelCase_ : Optional[Any] = [aliases] lowerCAmelCase_ : Any = getattr(field.type , '''__origin__''' , field.type ) if origin_type is Union or (hasattr(__lowercase , '''UnionType''' ) and isinstance(__lowercase , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(__lowercase ) not in field.type.__args__ ): raise ValueError( '''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because''' ''' the argument parser only supports one type per argument.''' f""" Problem encountered in field '{field.name}'.""" ) if type(__lowercase ) not in field.type.__args__: # filter `str` in Union lowerCAmelCase_ : List[Any] = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] lowerCAmelCase_ : Dict = getattr(field.type , '''__origin__''' , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) lowerCAmelCase_ : str = ( field.type.__args__[0] if isinstance(__lowercase , field.type.__args__[1] ) else field.type.__args__[1] ) lowerCAmelCase_ : List[Any] = getattr(field.type , '''__origin__''' , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) lowerCAmelCase_ : Dict = {} if origin_type is Literal or (isinstance(field.type , __lowercase ) and issubclass(field.type , __lowercase )): if origin_type is Literal: lowerCAmelCase_ : Optional[Any] = field.type.__args__ else: lowerCAmelCase_ : int = [x.value for x in field.type] lowerCAmelCase_ : str = make_choice_type_function(kwargs['''choices'''] ) if field.default is not dataclasses.MISSING: lowerCAmelCase_ : str = field.default else: lowerCAmelCase_ : Tuple = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument lowerCAmelCase_ : Tuple = copy(__lowercase ) # Hack because type=bool in argparse does not behave as we want. lowerCAmelCase_ : Dict = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. lowerCAmelCase_ : Union[str, Any] = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way lowerCAmelCase_ : List[str] = default # This tells argparse we accept 0 or 1 value after --field_name lowerCAmelCase_ : int = '''?''' # This is the value that will get picked if we do --field_name (without value) lowerCAmelCase_ : List[Any] = True elif isclass(__lowercase ) and issubclass(__lowercase , __lowercase ): lowerCAmelCase_ : Union[str, Any] = field.type.__args__[0] lowerCAmelCase_ : Dict = '''+''' if field.default_factory is not dataclasses.MISSING: lowerCAmelCase_ : Any = field.default_factory() elif field.default is dataclasses.MISSING: lowerCAmelCase_ : Optional[int] = True else: lowerCAmelCase_ : List[Any] = field.type if field.default is not dataclasses.MISSING: lowerCAmelCase_ : Dict = field.default elif field.default_factory is not dataclasses.MISSING: lowerCAmelCase_ : List[Any] = field.default_factory() else: lowerCAmelCase_ : int = True parser.add_argument(__lowercase , *__lowercase , **__lowercase ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): lowerCAmelCase_ : Any = False parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__lowercase ) def lowercase_ ( self , __lowercase ) -> List[Any]: if hasattr(__lowercase , '''_argument_group_name''' ): lowerCAmelCase_ : str = self.add_argument_group(dtype._argument_group_name ) else: lowerCAmelCase_ : Dict = self try: lowerCAmelCase_ : Dict[str, type] = get_type_hints(__lowercase ) except NameError: raise RuntimeError( f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """ '''removing line of `from __future__ import annotations` which opts in Postponed ''' '''Evaluation of Annotations (PEP 563)''' ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(__lowercase ): lowerCAmelCase_ : Any = '''.'''.join(map(__lowercase , sys.version_info[:3] ) ) raise RuntimeError( f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """ '''line of `from __future__ import annotations` which opts in union types as ''' '''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To ''' '''support Python versions that lower than 3.10, you need to use ''' '''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of ''' '''`X | None`.''' ) from ex raise for field in dataclasses.fields(__lowercase ): if not field.init: continue lowerCAmelCase_ : Optional[int] = type_hints[field.name] self._parse_dataclass_field(__lowercase , __lowercase ) def lowercase_ ( self , __lowercase=None , __lowercase=False , __lowercase=True , __lowercase=None , __lowercase=None , ) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): lowerCAmelCase_ : str = [] if args_filename: args_files.append(Path(__lowercase ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values lowerCAmelCase_ : str = ArgumentParser() args_file_parser.add_argument(__lowercase , type=__lowercase , action='''append''' ) # Use only remaining args for further parsing (remove the args_file_flag) lowerCAmelCase_ , lowerCAmelCase_ : Tuple = args_file_parser.parse_known_args(args=__lowercase ) lowerCAmelCase_ : int = vars(__lowercase ).get(args_file_flag.lstrip('''-''' ) , __lowercase ) if cmd_args_file_paths: args_files.extend([Path(__lowercase ) for p in cmd_args_file_paths] ) lowerCAmelCase_ : Dict = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last lowerCAmelCase_ : Any = file_args + args if args is not None else file_args + sys.argv[1:] lowerCAmelCase_ , lowerCAmelCase_ : Dict = self.parse_known_args(args=__lowercase ) lowerCAmelCase_ : Any = [] for dtype in self.dataclass_types: lowerCAmelCase_ : str = {f.name for f in dataclasses.fields(__lowercase ) if f.init} lowerCAmelCase_ : str = {k: v for k, v in vars(__lowercase ).items() if k in keys} for k in keys: delattr(__lowercase , __lowercase ) lowerCAmelCase_ : Optional[int] = dtype(**__lowercase ) outputs.append(__lowercase ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(__lowercase ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" ) return (*outputs,) def lowercase_ ( self , __lowercase , __lowercase = False ) -> Tuple[DataClass, ...]: lowerCAmelCase_ : int = set(args.keys() ) lowerCAmelCase_ : str = [] for dtype in self.dataclass_types: lowerCAmelCase_ : int = {f.name for f in dataclasses.fields(__lowercase ) if f.init} lowerCAmelCase_ : List[str] = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) lowerCAmelCase_ : List[str] = dtype(**__lowercase ) outputs.append(__lowercase ) if not allow_extra_keys and unused_keys: raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__lowercase )}""" ) return tuple(__lowercase ) def lowercase_ ( self , __lowercase , __lowercase = False ) -> Tuple[DataClass, ...]: with open(Path(__lowercase ) , encoding='''utf-8''' ) as open_json_file: lowerCAmelCase_ : Dict = json.loads(open_json_file.read() ) lowerCAmelCase_ : str = self.parse_dict(__lowercase , allow_extra_keys=__lowercase ) return tuple(__lowercase ) def lowercase_ ( self , __lowercase , __lowercase = False ) -> Tuple[DataClass, ...]: lowerCAmelCase_ : Optional[Any] = self.parse_dict(yaml.safe_load(Path(__lowercase ).read_text() ) , allow_extra_keys=__lowercase ) return tuple(__lowercase )
262
0
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer __UpperCamelCase = ['''bert-base-uncased''', '''bert-base-cased'''] __UpperCamelCase = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class UpperCamelCase ( tf.keras.Model ): def __init__( self, lowerCAmelCase__) -> Dict: super().__init__() snake_case_ = tokenizer snake_case_ = AutoConfig.from_pretrained(lowerCAmelCase__) snake_case_ = TFAutoModel.from_config(lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> List[str]: snake_case_ = self.tokenizer(lowerCAmelCase__) snake_case_ = self.bert(**lowerCAmelCase__) return out["pooler_output"] @require_tf @require_tensorflow_text class UpperCamelCase ( unittest.TestCase ): def a_ ( self) -> Optional[Any]: super().setUp() snake_case_ = [ BertTokenizer.from_pretrained(lowerCAmelCase__) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false snake_case_ = [TFBertTokenizer.from_pretrained(lowerCAmelCase__) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(lowerCAmelCase__, use_fast_bert_tokenizer=lowerCAmelCase__) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers) == len(self.tf_tokenizers) snake_case_ = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] snake_case_ = list(zip(self.test_sentences, self.test_sentences[::-1])) def a_ ( self) -> List[str]: for tokenizer, tf_tokenizer in zip(self.tokenizers, self.tf_tokenizers): for test_inputs in (self.test_sentences, self.paired_sentences): snake_case_ = tokenizer(lowerCAmelCase__, return_tensors='tf', padding='longest') snake_case_ = tf_tokenizer(lowerCAmelCase__) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape)) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key], tf.intaa) == tf_outputs[key])) @slow def a_ ( self) -> int: for tf_tokenizer in self.tf_tokenizers: snake_case_ = tf_tokenizer(self.paired_sentences) snake_case_ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences], text_pair=[sentence[1] for sentence in self.paired_sentences], ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key], tf.intaa) == separated_outputs[key])) @slow def a_ ( self) -> Optional[int]: for tf_tokenizer in self.tf_tokenizers: snake_case_ = tf.function(lowerCAmelCase__) for test_inputs in (self.test_sentences, self.paired_sentences): snake_case_ = tf.constant(lowerCAmelCase__) snake_case_ = compiled_tokenizer(lowerCAmelCase__) snake_case_ = tf_tokenizer(lowerCAmelCase__) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key])) @slow def a_ ( self) -> int: for tf_tokenizer in self.tf_tokenizers: snake_case_ = ModelToSave(tokenizer=lowerCAmelCase__) snake_case_ = tf.convert_to_tensor(self.test_sentences) snake_case_ = model(lowerCAmelCase__) # Build model with some sample inputs with TemporaryDirectory() as tempdir: snake_case_ = Path(lowerCAmelCase__) / 'saved.model' model.save(lowerCAmelCase__) snake_case_ = tf.keras.models.load_model(lowerCAmelCase__) snake_case_ = loaded_model(lowerCAmelCase__) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output)), 1e-5)
312
"""simple docstring""" from __future__ import annotations def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> list[str]: if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) snake_case_ = number_of_bytes // partitions snake_case_ = [] for i in range(UpperCAmelCase ): snake_case_ = i * bytes_per_partition + 1 snake_case_ = ( 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()
312
1
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : NDArray[floataa] , SCREAMING_SNAKE_CASE : NDArray[floataa] , SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int , ): '''simple docstring''' lowerCAmelCase = coefficient_matrix.shape lowerCAmelCase = constant_matrix.shape if rowsa != colsa: lowerCAmelCase = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(lowerCAmelCase_ ) if colsa != 1: lowerCAmelCase = F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(lowerCAmelCase_ ) if rowsa != rowsa: lowerCAmelCase = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != rowsa: lowerCAmelCase = ( """Number of initial values must be equal to number of rows in coefficient """ F'matrix but received {len(lowerCAmelCase_ )} and {rowsa}' ) raise ValueError(lowerCAmelCase_ ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) lowerCAmelCase = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) lowerCAmelCase = table.shape strictly_diagonally_dominant(lowerCAmelCase_ ) # Iterates the whole matrix for given number of times for _ in range(lowerCAmelCase_ ): lowerCAmelCase = [] for row in range(lowerCAmelCase_ ): lowerCAmelCase = 0 for col in range(lowerCAmelCase_ ): if col == row: lowerCAmelCase = table[row][col] elif col == cols - 1: lowerCAmelCase = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] lowerCAmelCase = (temp + val) / denom new_val.append(lowerCAmelCase_ ) lowerCAmelCase = new_val return [float(lowerCAmelCase_ ) for i in new_val] def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : NDArray[floataa] ): '''simple docstring''' lowerCAmelCase = table.shape lowerCAmelCase = True for i in range(0 , lowerCAmelCase_ ): lowerCAmelCase = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
46
from maths.prime_check import is_prime def snake_case_ ( lowerCAmelCase_ : int ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __lowercase : Dict = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCAmelCase_ ) if is_prime(lowerCAmelCase_ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
233
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class __a ( __UpperCamelCase ): @staticmethod @abstractmethod def A ( UpperCAmelCase : ArgumentParser ): raise NotImplementedError() @abstractmethod def A ( self : str ): raise NotImplementedError()
351
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __UpperCAmelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
28
0
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowercase__ : Union[str, Any] = float("nan") class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] , __lowercase : str ): """simple docstring""" snake_case_ = sys.stdout snake_case_ = open(SCREAMING_SNAKE_CASE__ , "a" ) def __getattr__( self : Dict , __lowercase : Any ): """simple docstring""" return getattr(self.stdout , SCREAMING_SNAKE_CASE__ ) def snake_case__ ( self : Optional[Any] , __lowercase : Dict ): """simple docstring""" self.stdout.write(SCREAMING_SNAKE_CASE__ ) # strip tqdm codes self.file.write(re.sub(r"^.*\r" , "" , SCREAMING_SNAKE_CASE__ , 0 , re.M ) ) def lowerCamelCase__ ( _A=80 , _A=False ): '''simple docstring''' snake_case_ = [] # deal with critical env vars snake_case_ = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: snake_case_ = os.environ.get(__lowerCAmelCase , __lowerCAmelCase ) if val is not None: cmd.append(f"{key}={val}" ) # python executable (not always needed if the script is executable) snake_case_ = sys.executable if full_python_path else sys.executable.split("/" )[-1] cmd.append(__lowerCAmelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes snake_case_ = [] snake_case_ = "" while len(__lowerCAmelCase ) > 0: current_line += f"{cmd.pop(0 )} " if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__lowerCAmelCase ) snake_case_ = "" return "\\\n".join(__lowerCAmelCase ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' snake_case_ = re.sub(R"[\\\n]+" , " " , args.base_cmd ) # remove --output_dir if any and set our own snake_case_ = re.sub("--output_dir\s+[^\s]+" , "" , args.base_cmd ) args.base_cmd += f" --output_dir {output_dir}" # ensure we have --overwrite_output_dir snake_case_ = re.sub("--overwrite_output_dir\s+" , "" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , ) snake_case_ = subprocess.run(__lowerCAmelCase , capture_output=__lowerCAmelCase , text=__lowerCAmelCase ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams snake_case_ = variation.replace(" " , "-" ) with open(Path(__lowerCAmelCase ) / f"log.{prefix}.stdout.txt" , "w" ) as f: f.write(result.stdout ) with open(Path(__lowerCAmelCase ) / f"log.{prefix}.stderr.txt" , "w" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("failed" ) return {target_metric_key: nan} with io.open(f"{output_dir}/all_results.json" , "r" , encoding="utf-8" ) as f: snake_case_ = json.load(__lowerCAmelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): '''simple docstring''' snake_case_ = [] snake_case_ = [] snake_case_ = f"{id}: {variation:<{longest_variation_len}}" snake_case_ = f"{preamble}: " snake_case_ = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__lowerCAmelCase ) , desc=__lowerCAmelCase , leave=__lowerCAmelCase ): snake_case_ = process_run_single( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) snake_case_ = single_run_metrics[target_metric_key] if not math.isnan(__lowerCAmelCase ): metrics.append(__lowerCAmelCase ) results.append(__lowerCAmelCase ) outcome += "✓" else: outcome += "✘" snake_case_ = f"\33[2K\r{outcome}" if len(__lowerCAmelCase ) > 0: snake_case_ = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} snake_case_ = round(mean_metrics[target_metric_key] , 2 ) snake_case_ = f"{outcome} {mean_target}" if len(__lowerCAmelCase ) > 1: results_str += f" {tuple(round(__lowerCAmelCase , 2 ) for x in results )}" print(__lowerCAmelCase ) snake_case_ = variation return mean_metrics else: print(__lowerCAmelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCamelCase__ ( ): '''simple docstring''' snake_case_ = torch.cuda.get_device_properties(torch.device("cuda" ) ) return f"\nDatetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n" def lowerCamelCase__ ( _A , _A , _A , _A , _A ): '''simple docstring''' snake_case_ = pd.DataFrame(__lowerCAmelCase ) snake_case_ = "variation" snake_case_ = "diff_%" snake_case_ = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan snake_case_ = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__lowerCAmelCase ): # as a fallback, use the minimal value as the sentinel snake_case_ = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__lowerCAmelCase ): snake_case_ = df.apply( lambda _A : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="columns" , ) # re-order columns snake_case_ = [variation_key, target_metric_key, diff_key, *report_metric_keys] snake_case_ = df.reindex(__lowerCAmelCase , axis="columns" ) # reorder cols # capitalize snake_case_ = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible snake_case_ = df.rename(lambda _A : c.replace("_" , "<br>" ) , axis="columns" ) snake_case_ = df.rename(lambda _A : c.replace("_" , "\n" ) , axis="columns" ) snake_case_ = ["", "Copy between the cut-here-lines and paste as is to github or a forum"] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__lowerCAmelCase , floatfmt=".2f" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__lowerCAmelCase , floatfmt=".2f" )] print("\n\n".join(__lowerCAmelCase ) ) def lowerCamelCase__ ( ): '''simple docstring''' snake_case_ = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="Base cmd" , ) parser.add_argument( "--variations" , default=__lowerCAmelCase , type=__lowerCAmelCase , nargs="+" , required=__lowerCAmelCase , help="Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'" , ) parser.add_argument( "--base-variation" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="Baseline variation to compare to. if None the minimal target value will be used to compare against" , ) parser.add_argument( "--target-metric-key" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=__lowerCAmelCase , help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples" , ) parser.add_argument( "--repeat-times" , default=1 , type=__lowerCAmelCase , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=__lowerCAmelCase , help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked" , ) parser.add_argument( "--verbose" , default=__lowerCAmelCase , action="store_true" , help="Whether to show the outputs of each run or just the benchmark progress" , ) snake_case_ = parser.parse_args() snake_case_ = args.output_dir Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) snake_case_ = get_base_command(__lowerCAmelCase , __lowerCAmelCase ) # split each dimension into its --foo variations snake_case_ = [list(map(str.strip , re.split(R"\|" , __lowerCAmelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty snake_case_ = list(map(str.strip , map(" ".join , itertools.product(*__lowerCAmelCase ) ) ) ) snake_case_ = max(len(__lowerCAmelCase ) for x in variations ) # split wanted keys snake_case_ = args.report_metric_keys.split() # capture prints into a log file for convenience snake_case_ = f"benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S' )}.txt" print(f"\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt" ) print(f"and this script\'s output is also piped into {report_fn}" ) snake_case_ = Tee(__lowerCAmelCase ) print(f"\n*** Running {len(__lowerCAmelCase )} benchmarks:" ) print(f"Base command: {' '.join(__lowerCAmelCase )}" ) snake_case_ = "variation" snake_case_ = [] for id, variation in enumerate(tqdm(__lowerCAmelCase , desc="Total completion: " , leave=__lowerCAmelCase ) ): snake_case_ = base_cmd + variation.split() results.append( process_run( id + 1 , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.repeat_times , __lowerCAmelCase , args.verbose , ) ) process_results(__lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.base_variation , __lowerCAmelCase ) if __name__ == "__main__": main()
187
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> Optional[Any]: """simple docstring""" if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(__UpperCamelCase ): return ext raise Exception( f"""Unable to determine file format from file extension {path}. """ f"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) SCREAMING_SNAKE_CASE__ = try_infer_format_from_ext(args.input ) if args.format == """infer""" else args.format SCREAMING_SNAKE_CASE__ = PipelineDataFormat.from_str( format=__UpperCamelCase , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(__UpperCamelCase , __UpperCamelCase ) class __snake_case ( lowerCamelCase_ ): def __init__( self : int , _lowercase : Pipeline , _lowercase : PipelineDataFormat ): """simple docstring""" SCREAMING_SNAKE_CASE__ = nlp SCREAMING_SNAKE_CASE__ = reader @staticmethod def __a ( _lowercase : ArgumentParser ): """simple docstring""" SCREAMING_SNAKE_CASE__ = parser.add_parser("""run""" , help="""Run a pipeline through the CLI""" ) run_parser.add_argument("""--task""" , choices=get_supported_tasks() , help="""Task to run""" ) run_parser.add_argument("""--input""" , type=_lowercase , help="""Path to the file to use for inference""" ) run_parser.add_argument("""--output""" , type=_lowercase , help="""Path to the file that will be used post to write results.""" ) run_parser.add_argument("""--model""" , type=_lowercase , help="""Name or path to the model to instantiate.""" ) run_parser.add_argument("""--config""" , type=_lowercase , help="""Name or path to the model's config to instantiate.""" ) run_parser.add_argument( """--tokenizer""" , type=_lowercase , help="""Name of the tokenizer to use. (default: same as the model name)""" ) run_parser.add_argument( """--column""" , type=_lowercase , help="""Name of the column to use as input. (For multi columns input as QA use column1,columns2)""" , ) run_parser.add_argument( """--format""" , type=_lowercase , default="""infer""" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="""Input format to read from""" , ) run_parser.add_argument( """--device""" , type=_lowercase , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) run_parser.add_argument("""--overwrite""" , action="""store_true""" , help="""Allow overwriting the output file.""" ) run_parser.set_defaults(func=_lowercase ) def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self._nlp, [] for entry in self._reader: SCREAMING_SNAKE_CASE__ = nlp(**_lowercase ) if self._reader.is_multi_columns else nlp(_lowercase ) if isinstance(_lowercase , _lowercase ): outputs.append(_lowercase ) else: outputs += output # Saving data if self._nlp.binary_output: SCREAMING_SNAKE_CASE__ = self._reader.save_binary(_lowercase ) logger.warning(f"""Current pipeline requires output to be in binary format, saving at {binary_path}""" ) else: self._reader.save(_lowercase )
365
from __future__ import annotations __lowerCamelCase : Dict = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __lowerCamelCase : Union[str, Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[float] ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = len(__UpperCamelCase ) for i in range(__UpperCamelCase ): SCREAMING_SNAKE_CASE__ = -1 for j in range(i + 1 , __UpperCamelCase ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE__ = arr[j] break result.append(__UpperCamelCase ) return result def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[float] ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] for i, outer in enumerate(__UpperCamelCase ): SCREAMING_SNAKE_CASE__ = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE__ = inner break result.append(__UpperCamelCase ) return result def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : list[float] ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE__ = len(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [-1] * arr_size for index in reversed(range(__UpperCamelCase ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE__ = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __lowerCamelCase : List[Any] = ( '''from __main__ import arr, next_greatest_element_slow, ''' '''next_greatest_element_fast, next_greatest_element''' ) print( '''next_greatest_element_slow():''', timeit('''next_greatest_element_slow(arr)''', setup=setup), ) print( '''next_greatest_element_fast():''', timeit('''next_greatest_element_fast(arr)''', setup=setup), ) print( ''' next_greatest_element():''', timeit('''next_greatest_element(arr)''', setup=setup), )
204
0
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def __lowerCamelCase ( lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[str]=False ): '''simple docstring''' try: lowerCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. lowerCamelCase = default else: # KEY is set, convert it to True or False. try: lowerCamelCase = strtobool(__snake_case ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f'If set, {key} must be yes or no.' ) return _value UpperCAmelCase : Union[str, Any] = parse_flag_from_env("RUN_SLOW", default=False) def __lowerCamelCase ( lowerCamelCase__ : int ): '''simple docstring''' return unittest.skip("""Test was skipped""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests , """test is slow""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() , """test requires only a CPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() , """test requires a GPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' return unittest.skipUnless(is_xpu_available() , """test requires a XPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : str ): '''simple docstring''' return unittest.skipUnless(is_mps_available() , """test requires a `mps` backend support in `torch`""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() , """test requires the Hugging Face suite""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : str ): '''simple docstring''' return unittest.skipUnless(is_bnb_available() , """test requires the bitsandbytes library""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Dict ): '''simple docstring''' return unittest.skipUnless(is_tpu_available() , """test requires TPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 , """test requires a GPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Dict ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 , """test requires a XPU""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 , """test requires multiple GPUs""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : int ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 , """test requires multiple XPUs""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Dict ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available() , """test requires safetensors""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() , """test requires DeepSpeed""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_torch_version(""">=""" , """1.12.0""" ) , """test requires torch version >= 1.12.0""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Dict=None , lowerCamelCase__ : Dict=None ): '''simple docstring''' if test_case is None: return partial(__snake_case , version=__snake_case ) return unittest.skipUnless(is_torch_version(""">=""" , __snake_case ) , f'test requires torch version >= {version}' )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : str ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() , """test requires Tensorboard""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' return unittest.skipUnless(is_wandb_available() , """test requires wandb""" )(__snake_case ) def __lowerCamelCase ( lowerCamelCase__ : str ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() , """test requires comet_ml""" )(__snake_case ) UpperCAmelCase : List[Any] = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def __lowerCamelCase ( lowerCamelCase__ : List[Any] ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available , """test requires at least one tracker to be available and for `comet_ml` to not be installed""" , )(__snake_case ) class __lowercase ( unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = True @classmethod def __A ( cls ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = tempfile.mkdtemp() @classmethod def __A ( cls ) -> List[str]: '''simple docstring''' if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def __A ( self ) -> str: '''simple docstring''' if self.clear_on_setup: for path in Path(self.tmpdir ).glob("""**/*""" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(_UpperCamelCase ) class __lowercase ( unittest.TestCase ): """simple docstring""" def __A ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class __lowercase ( unittest.TestCase ): """simple docstring""" def __A ( self , A ) -> Any: '''simple docstring''' lowerCamelCase = mocks if isinstance(_UpperCamelCase , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def __lowerCamelCase ( lowerCamelCase__ : int ): '''simple docstring''' lowerCamelCase = AcceleratorState() lowerCamelCase = tensor[None].clone().to(state.device ) lowerCamelCase = gather(__snake_case ).cpu() lowerCamelCase = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , __snake_case ): return False return True class __lowercase : """simple docstring""" def __init__( self , A , A , A ) -> Any: '''simple docstring''' lowerCamelCase = returncode lowerCamelCase = stdout lowerCamelCase = stderr async def __lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int] ): '''simple docstring''' while True: lowerCamelCase = await stream.readline() if line: callback(__snake_case ) else: break async def __lowerCamelCase ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Dict=None , lowerCamelCase__ : str=None , lowerCamelCase__ : Dict=None , lowerCamelCase__ : List[str]=False , lowerCamelCase__ : Optional[int]=False ): '''simple docstring''' if echo: print("""\nRunning: """ , """ """.join(__snake_case ) ) lowerCamelCase = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=__snake_case , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=__snake_case , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) lowerCamelCase = [] lowerCamelCase = [] def tee(lowerCamelCase__ : Dict , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int]="" ): lowerCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__snake_case ) if not quiet: print(__snake_case , __snake_case , file=__snake_case ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda lowerCamelCase__ : tee(__snake_case , __snake_case , sys.stdout , label="""stdout:""" ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda lowerCamelCase__ : tee(__snake_case , __snake_case , sys.stderr , label="""stderr:""" ) ) ), ] , timeout=__snake_case , ) return _RunOutput(await p.wait() , __snake_case , __snake_case ) def __lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : str=None , lowerCamelCase__ : Tuple=180 , lowerCamelCase__ : Dict=False , lowerCamelCase__ : Optional[Any]=True ): '''simple docstring''' lowerCamelCase = asyncio.get_event_loop() lowerCamelCase = loop.run_until_complete( _stream_subprocess(__snake_case , env=__snake_case , stdin=__snake_case , timeout=__snake_case , quiet=__snake_case , echo=__snake_case ) ) lowerCamelCase = ' '.join(__snake_case ) if result.returncode > 0: lowerCamelCase = '\n'.join(result.stderr ) raise RuntimeError( f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n' f'The combined stderr from workers follows:\n{stderr}' ) return result class __lowercase ( _snake_case ): """simple docstring""" pass def __lowerCamelCase ( lowerCamelCase__ : List[str] , lowerCamelCase__ : List[Any]=False ): '''simple docstring''' try: lowerCamelCase = subprocess.check_output(__snake_case , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(__snake_case , """decode""" ): lowerCamelCase = output.decode("""utf-8""" ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( f'Command `{" ".join(__snake_case )}` failed with the following error:\n\n{e.output.decode()}' ) from e
252
import os # Precomputes a list of the 100 first triangular numbers __UpperCAmelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowercase__ ( ): '''simple docstring''' UpperCAmelCase_ : Any = os.path.dirname(os.path.realpath(__snake_case ) ) UpperCAmelCase_ : Optional[Any] = os.path.join(__snake_case , 'words.txt' ) UpperCAmelCase_ : Union[str, Any] = '' with open(__snake_case ) as f: UpperCAmelCase_ : List[Any] = f.readline() UpperCAmelCase_ : Optional[int] = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] UpperCAmelCase_ : Optional[int] = [ word for word in [sum(ord(__snake_case ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__snake_case ) if __name__ == "__main__": print(solution())
29
0
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" a : Optional[int] =[r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = 5_0_2_5_7 , _lowerCamelCase = 1_0_2_4 , _lowerCamelCase = 7_6_8 , _lowerCamelCase = 1_2 , _lowerCamelCase = 1_2 , _lowerCamelCase = None , _lowerCamelCase = "gelu_new" , _lowerCamelCase = 0.1 , _lowerCamelCase = 0.1 , _lowerCamelCase = 0.1 , _lowerCamelCase = 1e-5 , _lowerCamelCase = 0.0_2 , _lowerCamelCase = True , _lowerCamelCase = True , _lowerCamelCase = False , _lowerCamelCase = False , ): super().__init__() UpperCamelCase_: str = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) UpperCamelCase_: Any = prefix_inner_dim UpperCamelCase_: Dict = prefix_hidden_dim UpperCamelCase_: int = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCamelCase_: Tuple = ( nn.Linear(self.prefix_hidden_dim , _lowerCamelCase ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCamelCase_: Union[str, Any] = GPTaConfig( vocab_size=_lowerCamelCase , n_positions=_lowerCamelCase , n_embd=_lowerCamelCase , n_layer=_lowerCamelCase , n_head=_lowerCamelCase , n_inner=_lowerCamelCase , activation_function=_lowerCamelCase , resid_pdrop=_lowerCamelCase , embd_pdrop=_lowerCamelCase , attn_pdrop=_lowerCamelCase , layer_norm_epsilon=_lowerCamelCase , initializer_range=_lowerCamelCase , scale_attn_weights=_lowerCamelCase , use_cache=_lowerCamelCase , scale_attn_by_inverse_layer_idx=_lowerCamelCase , reorder_and_upcast_attn=_lowerCamelCase , ) UpperCamelCase_: Optional[Any] = GPTaLMHeadModel(_lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , ): UpperCamelCase_: Any = self.transformer.transformer.wte(_lowerCamelCase ) UpperCamelCase_: Any = self.encode_prefix(_lowerCamelCase ) UpperCamelCase_: Tuple = self.decode_prefix(_lowerCamelCase ) UpperCamelCase_: Optional[int] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: UpperCamelCase_: Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) UpperCamelCase_: str = torch.cat((dummy_token, input_ids) , dim=1 ) UpperCamelCase_: int = self.transformer(inputs_embeds=_lowerCamelCase , labels=_lowerCamelCase , attention_mask=_lowerCamelCase ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , _lowerCamelCase , _lowerCamelCase ): return torch.zeros(_lowerCamelCase , self.prefix_length , dtype=torch.intaa , device=_lowerCamelCase ) def _a ( self , _lowerCamelCase ): return self.encode_prefix(_lowerCamelCase ) @torch.no_grad() def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[Any] = torch.split(_lowerCamelCase , 1 , dim=0 ) UpperCamelCase_: Optional[Any] = [] UpperCamelCase_: Optional[int] = [] for feature in features: UpperCamelCase_: Tuple = self.decode_prefix(feature.to(_lowerCamelCase ) ) # back to the clip feature # Only support beam search for now UpperCamelCase_ ,UpperCamelCase_: Optional[Any] = self.generate_beam( input_embeds=_lowerCamelCase , device=_lowerCamelCase , eos_token_id=_lowerCamelCase ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) UpperCamelCase_: Any = torch.stack(_lowerCamelCase ) UpperCamelCase_: Tuple = torch.stack(_lowerCamelCase ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase = 5 , _lowerCamelCase = 6_7 , _lowerCamelCase = 1.0 , _lowerCamelCase = None , ): UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Tuple = None UpperCamelCase_: Optional[Any] = None UpperCamelCase_: List[Any] = torch.ones(_lowerCamelCase , device=_lowerCamelCase , dtype=torch.int ) UpperCamelCase_: int = torch.zeros(_lowerCamelCase , device=_lowerCamelCase , dtype=torch.bool ) if input_embeds is not None: UpperCamelCase_: List[str] = input_embeds else: UpperCamelCase_: str = self.transformer.transformer.wte(_lowerCamelCase ) for i in range(_lowerCamelCase ): UpperCamelCase_: Dict = self.transformer(inputs_embeds=_lowerCamelCase ) UpperCamelCase_: Any = outputs.logits UpperCamelCase_: Optional[Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) UpperCamelCase_: str = logits.softmax(-1 ).log() if scores is None: UpperCamelCase_ ,UpperCamelCase_: List[Any] = logits.topk(_lowerCamelCase , -1 ) UpperCamelCase_: Union[str, Any] = generated.expand(_lowerCamelCase , *generated.shape[1:] ) UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: UpperCamelCase_: Optional[Any] = next_tokens else: UpperCamelCase_: Tuple = tokens.expand(_lowerCamelCase , *tokens.shape[1:] ) UpperCamelCase_: Optional[int] = torch.cat((tokens, next_tokens) , dim=1 ) else: UpperCamelCase_: Tuple = -float(np.inf ) UpperCamelCase_: Tuple = 0 UpperCamelCase_: Optional[Any] = scores[:, None] + logits seq_lengths[~is_stopped] += 1 UpperCamelCase_: Optional[int] = scores_sum / seq_lengths[:, None] UpperCamelCase_ ,UpperCamelCase_: str = scores_sum_average.view(-1 ).topk(_lowerCamelCase , -1 ) UpperCamelCase_: List[str] = next_tokens // scores_sum.shape[1] UpperCamelCase_: Union[str, Any] = seq_lengths[next_tokens_source] UpperCamelCase_: int = next_tokens % scores_sum.shape[1] UpperCamelCase_: Optional[Any] = next_tokens.unsqueeze(1 ) UpperCamelCase_: Dict = tokens[next_tokens_source] UpperCamelCase_: List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) UpperCamelCase_: List[Any] = generated[next_tokens_source] UpperCamelCase_: Union[str, Any] = scores_sum_average * seq_lengths UpperCamelCase_: List[Any] = is_stopped[next_tokens_source] UpperCamelCase_: Tuple = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) UpperCamelCase_: int = torch.cat((generated, next_token_embed) , dim=1 ) UpperCamelCase_: Dict = is_stopped + next_tokens.eq(_lowerCamelCase ).squeeze() if is_stopped.all(): break UpperCamelCase_: Optional[Any] = scores / seq_lengths UpperCamelCase_: str = scores.argsort(descending=_lowerCamelCase ) # tokens tensors are already padded to max_seq_length UpperCamelCase_: Dict = [tokens[i] for i in order] UpperCamelCase_: Optional[int] = torch.stack(_lowerCamelCase , dim=0 ) UpperCamelCase_: Optional[Any] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
292
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params A_ : Tuple = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def snake_case (UpperCAmelCase__ ) -> str: for pegasus_name, hf_name in PATTERNS: UpperCamelCase_: List[str] = k.replace(UpperCAmelCase__ , UpperCAmelCase__ ) return k def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> PegasusForConditionalGeneration: UpperCamelCase_: List[str] = DEFAULTS.copy() cfg_kwargs.update(UpperCAmelCase__ ) UpperCamelCase_: Tuple = PegasusConfig(**UpperCAmelCase__ ) UpperCamelCase_: Tuple = PegasusForConditionalGeneration(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = torch_model.model.state_dict() UpperCamelCase_: str = {} for k, v in tf_weights.items(): UpperCamelCase_: Dict = rename_state_dict_key(UpperCAmelCase__ ) if new_k not in sd: raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''' ) if "dense" in k or "proj" in new_k: UpperCamelCase_: int = v.T UpperCamelCase_: Union[str, Any] = torch.tensor(UpperCAmelCase__ , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}''' # make sure embedding.padding_idx is respected UpperCamelCase_: Tuple = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] ) UpperCamelCase_: int = mapping['shared.weight'] UpperCamelCase_: Union[str, Any] = mapping['shared.weight'] UpperCamelCase_: Dict = {k: torch.zeros_like(UpperCAmelCase__ ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping} mapping.update(**UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_: Optional[int] = torch_model.model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) UpperCamelCase_: List[str] = [ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], F'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], F'''no matches found for the following tf keys {extra}''' return torch_model def snake_case (UpperCAmelCase__="./ckpt/aeslc/model.ckpt-32000" ) -> Dict: UpperCamelCase_: Union[str, Any] = tf.train.list_variables(UpperCAmelCase__ ) UpperCamelCase_: Tuple = {} UpperCamelCase_: Dict = ['Adafactor', 'global_step'] for name, shape in tqdm(UpperCAmelCase__ , desc='converting tf checkpoint to dict' ): UpperCamelCase_: Union[str, Any] = any(pat in name for pat in ignore_name ) if skip_key: continue UpperCamelCase_: Dict = tf.train.load_variable(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = array return tf_weights def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # save tokenizer first UpperCamelCase_: Any = Path(UpperCAmelCase__ ).parent.name UpperCamelCase_: Tuple = task_specific_params[F'''summarization_{dataset}''']['max_position_embeddings'] UpperCamelCase_: Optional[Any] = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=UpperCAmelCase__ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(UpperCAmelCase__ ) # convert model UpperCamelCase_: Optional[Any] = get_tf_weights_as_numpy(UpperCAmelCase__ ) UpperCamelCase_: Any = task_specific_params[F'''summarization_{dataset}'''] if dataset == "large": UpperCamelCase_: Union[str, Any] = task_specific_params UpperCamelCase_: Tuple = convert_pegasus(UpperCAmelCase__ , UpperCAmelCase__ ) torch_model.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = torch_model.state_dict() sd.pop('model.decoder.embed_positions.weight' ) sd.pop('model.encoder.embed_positions.weight' ) torch.save(UpperCAmelCase__ , Path(UpperCAmelCase__ ) / 'pytorch_model.bin' ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') A_ : Optional[Any] = parser.parse_args() if args.save_dir is None: A_ : Union[str, Any] = Path(args.tf_ckpt_path).parent.name A_ : Optional[Any] = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
292
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''facebook/s2t-small-librispeech-asr''': ( '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json''' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class SCREAMING_SNAKE_CASE__ ( lowercase ): """simple docstring""" a : str ="speech_to_text" a : Dict =["past_key_values"] a : Any ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , snake_case__=10_000 , snake_case__=12 , snake_case__=2_048 , snake_case__=4 , snake_case__=6 , snake_case__=2_048 , snake_case__=4 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=True , snake_case__=True , snake_case__="relu" , snake_case__=256 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.02 , snake_case__=2 , snake_case__=True , snake_case__=1 , snake_case__=0 , snake_case__=2 , snake_case__=6_000 , snake_case__=1_024 , snake_case__=2 , snake_case__=(5, 5) , snake_case__=1_024 , snake_case__=80 , snake_case__=1 , **snake_case__ , ): """simple docstring""" lowerCAmelCase : Dict = vocab_size lowerCAmelCase : List[Any] = d_model lowerCAmelCase : List[str] = encoder_ffn_dim lowerCAmelCase : int = encoder_layers lowerCAmelCase : Dict = encoder_attention_heads lowerCAmelCase : Optional[int] = decoder_ffn_dim lowerCAmelCase : str = decoder_layers lowerCAmelCase : Tuple = decoder_attention_heads lowerCAmelCase : Optional[int] = dropout lowerCAmelCase : int = attention_dropout lowerCAmelCase : Union[str, Any] = activation_dropout lowerCAmelCase : Any = activation_function lowerCAmelCase : Any = init_std lowerCAmelCase : Union[str, Any] = encoder_layerdrop lowerCAmelCase : List[str] = decoder_layerdrop lowerCAmelCase : List[str] = use_cache lowerCAmelCase : Dict = encoder_layers lowerCAmelCase : Any = scale_embedding # scale factor will be sqrt(d_model) if True lowerCAmelCase : Tuple = max_source_positions lowerCAmelCase : Optional[Any] = max_target_positions lowerCAmelCase : Optional[Any] = num_conv_layers lowerCAmelCase : Union[str, Any] = list(snake_case__ ) lowerCAmelCase : Any = conv_channels lowerCAmelCase : str = input_feat_per_channel lowerCAmelCase : List[Any] = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` " f"""but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, """ f"""`config.num_conv_layers = {self.num_conv_layers}`.""" ) super().__init__( pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , is_encoder_decoder=snake_case__ , decoder_start_token_id=snake_case__ , **snake_case__ , )
108
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowercase ( __UpperCAmelCase): __lowerCAmelCase : List[Any] = """layoutlmv3""" def __init__( self : Optional[int] , _lowerCamelCase : str=5_02_65 , _lowerCamelCase : Any=7_68 , _lowerCamelCase : int=12 , _lowerCamelCase : str=12 , _lowerCamelCase : int=30_72 , _lowerCamelCase : List[Any]="gelu" , _lowerCamelCase : Tuple=0.1 , _lowerCamelCase : str=0.1 , _lowerCamelCase : Any=5_12 , _lowerCamelCase : Tuple=2 , _lowerCamelCase : Dict=0.02 , _lowerCamelCase : Optional[Any]=1E-5 , _lowerCamelCase : Union[str, Any]=1 , _lowerCamelCase : Any=0 , _lowerCamelCase : int=2 , _lowerCamelCase : Union[str, Any]=10_24 , _lowerCamelCase : Dict=1_28 , _lowerCamelCase : int=1_28 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : int=32 , _lowerCamelCase : int=1_28 , _lowerCamelCase : Tuple=64 , _lowerCamelCase : List[Any]=2_56 , _lowerCamelCase : List[Any]=True , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : List[str]=True , _lowerCamelCase : Tuple=2_24 , _lowerCamelCase : List[Any]=3 , _lowerCamelCase : Dict=16 , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] , ): """simple docstring""" super().__init__( vocab_size=_lowerCamelCase , hidden_size=_lowerCamelCase , num_hidden_layers=_lowerCamelCase , num_attention_heads=_lowerCamelCase , intermediate_size=_lowerCamelCase , hidden_act=_lowerCamelCase , hidden_dropout_prob=_lowerCamelCase , attention_probs_dropout_prob=_lowerCamelCase , max_position_embeddings=_lowerCamelCase , type_vocab_size=_lowerCamelCase , initializer_range=_lowerCamelCase , layer_norm_eps=_lowerCamelCase , pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase , ) A_ : List[Any] = max_ad_position_embeddings A_ : List[str] = coordinate_size A_ : Tuple = shape_size A_ : Optional[Any] = has_relative_attention_bias A_ : Any = rel_pos_bins A_ : str = max_rel_pos A_ : Optional[int] = has_spatial_attention_bias A_ : int = rel_ad_pos_bins A_ : Tuple = max_rel_ad_pos A_ : int = text_embed A_ : List[Any] = visual_embed A_ : str = input_size A_ : Dict = num_channels A_ : Optional[int] = patch_size A_ : Dict = classifier_dropout class lowercase ( __UpperCAmelCase): __lowerCAmelCase : Optional[Any] = version.parse("""1.12""") @property def a_ ( self : Tuple ): """simple docstring""" if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def a_ ( self : int ): """simple docstring""" return 1E-5 @property def a_ ( self : Optional[int] ): """simple docstring""" return 12 def a_ ( self : Optional[int] , _lowerCamelCase : "ProcessorMixin" , _lowerCamelCase : int = -1 , _lowerCamelCase : int = -1 , _lowerCamelCase : bool = False , _lowerCamelCase : Optional["TensorType"] = None , _lowerCamelCase : int = 3 , _lowerCamelCase : int = 40 , _lowerCamelCase : int = 40 , ): """simple docstring""" setattr(processor.image_processor , '''apply_ocr''' , _lowerCamelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX A_ : Tuple = compute_effective_axis_dimension( _lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX A_ : Tuple = processor.tokenizer.num_special_tokens_to_add(_lowerCamelCase ) A_ : List[Any] = compute_effective_axis_dimension( _lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence A_ : int = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes A_ : Optional[int] = [[[48, 84, 73, 1_28]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) A_ : str = self._generate_dummy_images(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) A_ : Union[str, Any] = dict( processor( _lowerCamelCase , text=_lowerCamelCase , boxes=_lowerCamelCase , return_tensors=_lowerCamelCase , ) ) return inputs
167
0
import sys from collections import defaultdict class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = pos def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , _A ) self.top_to_bottom(_A , _A , _A , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , _A ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(_A , _A ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(_A , 0 ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = len(_A ) // 2 - 1 for i in range(_A , -1 , -1 ): self.top_to_bottom(_A , _A , len(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(_A , 0 , len(_A ) , _A ) return temp def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = [-1] * len(SCREAMING_SNAKE_CASE_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(SCREAMING_SNAKE_CASE_ ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE_ ) heap.node_position.append(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for _ in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): __lowerCAmelCase = heap.delete_minimum(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE_ )] ): __lowerCAmelCase = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE_ , heap.get_position(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCamelCase__ : Dict = int(input("""Enter number of edges: """).strip()) UpperCamelCase__ : List[Any] = defaultdict(list) for _ in range(edges_number): UpperCamelCase__ : List[str] = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
358
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) 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 from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class a__ ( snake_case__ ): _a : Optional[int] = """new-model""" if is_tf_available(): class a__ ( snake_case__ ): _a : Dict = NewModelConfig @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "bert-base-cased" __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModel.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "bert-base-cased" __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForPreTraining.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForCausalLM.from_pretrained(_A ) __lowerCAmelCase , __lowerCAmelCase = TFAutoModelForCausalLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForMaskedLM.from_pretrained(_A ) __lowerCAmelCase , __lowerCAmelCase = TFAutoModelForMaskedLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_A ) __lowerCAmelCase , __lowerCAmelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForSequenceClassification.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in ["bert-base-uncased"]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForQuestionAnswering.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow @require_tensorflow_probability def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __lowerCAmelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = TFAutoModelForTableQuestionAnswering.from_pretrained(_A ) __lowerCAmelCase , __lowerCAmelCase = TFAutoModelForTableQuestionAnswering.from_pretrained( _A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 1_4_4_1_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 1_4_4_1_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" ) self.assertIsInstance(_A , _A ) __lowerCAmelCase = copy.deepcopy(model.config ) __lowerCAmelCase = ["FunnelBaseModel"] __lowerCAmelCase = TFAutoModel.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __lowerCAmelCase = TFAutoModel.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" try: AutoConfig.register("new-model" , _A ) __lowerCAmelCase = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) auto_class.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) # Now that the config is registered, it can be used as any other config with the auto-API __lowerCAmelCase = BertModelTester(self ).get_config() __lowerCAmelCase = NewModelConfig(**tiny_config.to_dict() ) __lowerCAmelCase = auto_class.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __lowerCAmelCase = auto_class.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" with self.assertRaisesRegex( _A , "bert-base is not a local folder and is not a valid model identifier" ): __lowerCAmelCase = TFAutoModel.from_pretrained("bert-base" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" with self.assertRaisesRegex( _A , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): __lowerCAmelCase = TFAutoModel.from_pretrained(_A , revision="aaaaaa" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" with self.assertRaisesRegex( _A , "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin" , ): __lowerCAmelCase = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" with self.assertRaisesRegex(_A , "Use `from_pt=True` to load this model" ): __lowerCAmelCase = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) with RequestCounter() as counter: __lowerCAmelCase = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint __lowerCAmelCase = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) with RequestCounter() as counter: __lowerCAmelCase = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
102
0
class UpperCAmelCase : def __init__(self : Dict , snake_case__ : Optional[Any] ) -> List[Any]: '''simple docstring''' snake_case : Optional[int] = val snake_case : Any = None snake_case : Tuple = None def _SCREAMING_SNAKE_CASE (self : Tuple , snake_case__ : str ) -> Tuple: '''simple docstring''' if self.val: if val < self.val: if self.left is None: snake_case : Any = Node(snake_case__ ) else: self.left.insert(snake_case__ ) elif val > self.val: if self.right is None: snake_case : Tuple = Node(snake_case__ ) else: self.right.insert(snake_case__ ) else: snake_case : Optional[Any] = val def UpperCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int ): # Recursive traversal if root: inorder(root.left , __lowerCamelCase ) res.append(root.val ) inorder(root.right , __lowerCamelCase ) def UpperCamelCase ( __lowerCamelCase : Tuple ): # Build BST if len(__lowerCamelCase ) == 0: return arr snake_case : Optional[int] = Node(arr[0] ) for i in range(1 , len(__lowerCamelCase ) ): root.insert(arr[i] ) # Traverse BST in order. snake_case : Optional[int] = [] inorder(__lowerCamelCase , __lowerCamelCase ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
59
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() __lowerCamelCase = logging.get_logger() @dataclass class UpperCAmelCase : A__ : nn.Module A__ : List[nn.Module] = field(default_factory=A_ ) A__ : list = field(default_factory=A_ ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : Tensor , snake_case__ : Tensor ) -> Optional[Any]: '''simple docstring''' snake_case : List[str] = len(list(m.modules() ) ) == 1 or isinstance(snake_case__ , nn.Convad ) or isinstance(snake_case__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case__ ) def __call__(self : List[Any] , snake_case__ : Tensor ) -> List[Any]: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case__ ) [x.remove() for x in self.handles] return self @property def _SCREAMING_SNAKE_CASE (self : int ) -> Optional[int]: '''simple docstring''' return list(filter(lambda snake_case__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCAmelCase : A__ : nn.Module A__ : nn.Module A__ : int = 1 A__ : List = field(default_factory=A_ ) A__ : List = field(default_factory=A_ ) A__ : bool = True def __call__(self : List[Any] , snake_case__ : Tensor ) -> Any: '''simple docstring''' snake_case : str = Tracker(self.dest )(snake_case__ ).parametrized snake_case : Optional[int] = Tracker(self.src )(snake_case__ ).parametrized snake_case : List[str] = list(filter(lambda snake_case__ : type(snake_case__ ) not in self.src_skip , snake_case__ ) ) snake_case : Optional[Any] = list(filter(lambda snake_case__ : type(snake_case__ ) not in self.dest_skip , snake_case__ ) ) if len(snake_case__ ) != len(snake_case__ ) and self.raise_if_mismatch: raise Exception( f"""Numbers of operations are different. Source module has {len(snake_case__ )} operations while""" f""" destination module has {len(snake_case__ )}.""" ) for dest_m, src_m in zip(snake_case__ , snake_case__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) class UpperCAmelCase ( nn.Module ): def __init__(self : Tuple , snake_case__ : nn.Module ) -> Optional[Any]: '''simple docstring''' super().__init__() snake_case : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(("conv1", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("block" ), f"""Unexpected layer name {k}""" snake_case : Union[str, Any] = len(snake_case__ ) + 1 feature_blocks.append((f"""res{block_index}""", v) ) snake_case : Optional[Any] = nn.ModuleDict(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Tuple , snake_case__ : Tensor ) -> Dict: '''simple docstring''' return get_trunk_forward_outputs( snake_case__ , out_feat_keys=snake_case__ , feature_blocks=self._feature_blocks , ) class UpperCAmelCase ( A_ ): def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : str ) -> str: '''simple docstring''' snake_case : List[Any] = x.split("-" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__(self : Optional[int] , snake_case__ : str ) -> Callable[[], Tuple[nn.Module, Dict]]: '''simple docstring''' if x not in self: snake_case : Dict = self.convert_name_to_timm(snake_case__ ) snake_case : Union[str, Any] = partial(lambda: (timm.create_model(snake_case__ , pretrained=snake_case__ ).eval(), None) ) else: snake_case : List[str] = super().__getitem__(snake_case__ ) return val class UpperCAmelCase ( A_ ): def __getitem__(self : Dict , snake_case__ : str ) -> Callable[[], nn.Module]: '''simple docstring''' if "seer" in x and "in1k" not in x: snake_case : str = RegNetModel else: snake_case : Optional[Any] = RegNetForImageClassification return val def UpperCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Tuple[str, str]] ): for from_key, to_key in keys: snake_case : str = from_state_dict[from_key].clone() print(f"""Copied key={from_key} to={to_key}""" ) return to_state_dict def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Callable[[], nn.Module] , __lowerCamelCase : Callable[[], nn.Module] , __lowerCamelCase : RegNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True , ): print(f"""Converting {name}...""" ) with torch.no_grad(): snake_case , snake_case : int = from_model_func() snake_case : str = our_model_func(__lowerCamelCase ).eval() snake_case : int = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase , raise_if_mismatch=__lowerCamelCase ) snake_case : Dict = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) if from_state_dict is not None: snake_case : str = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: snake_case : Tuple = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] snake_case : Optional[Any] = manually_copy_vissl_head(__lowerCamelCase , our_model.state_dict() , __lowerCamelCase ) our_model.load_state_dict(__lowerCamelCase ) snake_case : Any = our_model(__lowerCamelCase , output_hidden_states=__lowerCamelCase ) snake_case : Union[str, Any] = ( our_outputs.logits if isinstance(__lowerCamelCase , __lowerCamelCase ) else our_outputs.last_hidden_state ) snake_case : Union[str, Any] = from_model(__lowerCamelCase ) snake_case : Dict = from_output[-1] if type(__lowerCamelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: snake_case : Any = our_outputs.hidden_states[-1] assert torch.allclose(__lowerCamelCase , __lowerCamelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add model" , use_temp_dir=__lowerCamelCase , ) snake_case : List[str] = 224 if "seer" not in name else 384 # we can use the convnext one snake_case : int = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" , size=__lowerCamelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add image processor" , use_temp_dir=__lowerCamelCase , ) print(f"""Pushed {name}""" ) def UpperCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ): snake_case : Union[str, Any] = "imagenet-1k-id2label.json" snake_case : List[str] = 1000 snake_case : List[str] = (1, num_labels) snake_case : Any = "huggingface/label-files" snake_case : List[str] = num_labels snake_case : Optional[Any] = json.load(open(cached_download(hf_hub_url(__lowerCamelCase , __lowerCamelCase , repo_type="dataset" ) ) , "r" ) ) snake_case : List[Any] = {int(__lowerCamelCase ): v for k, v in idalabel.items()} snake_case : str = idalabel snake_case : List[Any] = {v: k for k, v in idalabel.items()} snake_case : Dict = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) snake_case : Optional[Any] = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="x" ), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="x" ), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="x" ), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="x" ), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="x" ), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="x" ), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="x" ), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="x" ), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="x" ), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="x" ), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="x" ), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="x" ), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 11110, 28280] , groups_width=1010 ), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 11110, 28280] , groups_width=1010 ), } snake_case : Union[str, Any] = NameToOurModelFuncMap() snake_case : str = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(__lowerCamelCase : str , __lowerCamelCase : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: snake_case : List[Any] = torch.hub.load_state_dict_from_url(__lowerCamelCase , model_dir=str(__lowerCamelCase ) , map_location="cpu" ) snake_case : Dict = model_func() # check if we have a head, if yes add it snake_case : str = files["classy_state_dict"]["base_model"]["model"] snake_case : Dict = model_state_dict["trunk"] model.load_state_dict(__lowerCamelCase ) return model.eval(), model_state_dict["heads"] # pretrained snake_case : List[Any] = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : Optional[int] = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : List[str] = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) snake_case : Tuple = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned snake_case : List[Any] = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : Tuple = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : str = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) snake_case : Dict = partial( __lowerCamelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( __lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( __lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) return config, expected_shape if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported regnet* architecture,""" """ currently: regnetx-*, regnety-*. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) __lowerCamelCase = parser.parse_args() __lowerCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
59
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( 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 lowerCamelCase__ = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = ["pixel_values"] def __init__( self : Dict , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : bool = True , __a : Dict[str, int] = None , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = True , **__a : List[Any] , ) -> None: super().__init__(**__a ) _UpperCamelCase : List[str] = size if size is not None else {"shortest_edge": 224} _UpperCamelCase : str = get_size_dict(__a , default_to_square=__a ) _UpperCamelCase : Tuple = crop_size if crop_size is not None else {"height": 224, "width": 224} _UpperCamelCase : Tuple = get_size_dict(__a , default_to_square=__a , param_name="crop_size" ) _UpperCamelCase : List[str] = do_resize _UpperCamelCase : List[Any] = size _UpperCamelCase : Any = resample _UpperCamelCase : Union[str, Any] = do_center_crop _UpperCamelCase : List[str] = crop_size _UpperCamelCase : Tuple = do_rescale _UpperCamelCase : Tuple = rescale_factor _UpperCamelCase : List[str] = do_normalize _UpperCamelCase : Union[str, 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 : List[str] = do_convert_rgb def __SCREAMING_SNAKE_CASE ( self : str , __a : np.ndarray , __a : Dict[str, int] , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Dict , ) -> np.ndarray: _UpperCamelCase : Optional[int] = get_size_dict(__a , default_to_square=__a ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) _UpperCamelCase : str = get_resize_output_image_size(__a , size=size["shortest_edge"] , default_to_square=__a ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : str , __a : np.ndarray , __a : Dict[str, int] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[Any] , ) -> np.ndarray: _UpperCamelCase : str = get_size_dict(__a ) 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(__a , size=(size["height"], size["width"]) , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : np.ndarray , __a : Union[int, float] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Any , ) -> Optional[int]: return rescale(__a , scale=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : np.ndarray , __a : Union[float, List[float]] , __a : Union[float, List[float]] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[Any] , ) -> np.ndarray: return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : int = None , __a : bool = None , __a : float = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = None , __a : Optional[Union[str, TensorType]] = None , __a : Optional[ChannelDimension] = ChannelDimension.FIRST , **__a : str , ) -> PIL.Image.Image: _UpperCamelCase : str = do_resize if do_resize is not None else self.do_resize _UpperCamelCase : Union[str, Any] = size if size is not None else self.size _UpperCamelCase : Union[str, Any] = get_size_dict(__a , param_name="size" , default_to_square=__a ) _UpperCamelCase : Any = resample if resample is not None else self.resample _UpperCamelCase : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCamelCase : Optional[int] = crop_size if crop_size is not None else self.crop_size _UpperCamelCase : int = get_size_dict(__a , param_name="crop_size" , default_to_square=__a ) _UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale _UpperCamelCase : Any = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCamelCase : Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase : Optional[int] = image_mean if image_mean is not None else self.image_mean _UpperCamelCase : Any = image_std if image_std is not None else self.image_std _UpperCamelCase : Any = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _UpperCamelCase : str = make_list_of_images(__a ) if not valid_images(__a ): 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 : Tuple = [convert_to_rgb(__a ) for image in images] # All transformations expect numpy arrays. _UpperCamelCase : Optional[int] = [to_numpy_array(__a ) for image in images] if do_resize: _UpperCamelCase : Dict = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_center_crop: _UpperCamelCase : Dict = [self.center_crop(image=__a , size=__a ) for image in images] if do_rescale: _UpperCamelCase : Tuple = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: _UpperCamelCase : Optional[int] = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] _UpperCamelCase : Optional[Any] = [to_channel_dimension_format(__a , __a ) for image in images] _UpperCamelCase : List[str] = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
310
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: _UpperCamelCase : List[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) _UpperCamelCase : Union[str, Any] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__a ) _UpperCamelCase : Optional[int] = -1 _UpperCamelCase : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__a ) _UpperCamelCase : Union[str, Any] = model.generate(__a , max_new_tokens=10 , do_sample=__a ) _UpperCamelCase : Optional[Any] = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: _UpperCamelCase : Any = TextStreamer(__a ) model.generate(__a , max_new_tokens=10 , do_sample=__a , streamer=__a ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _UpperCamelCase : Optional[int] = cs.out[:-1] self.assertEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: _UpperCamelCase : List[str] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) _UpperCamelCase : Tuple = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__a ) _UpperCamelCase : Dict = -1 _UpperCamelCase : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__a ) _UpperCamelCase : List[str] = model.generate(__a , max_new_tokens=10 , do_sample=__a ) _UpperCamelCase : Optional[int] = tokenizer.decode(greedy_ids[0] ) _UpperCamelCase : Tuple = TextIteratorStreamer(__a ) _UpperCamelCase : Union[str, Any] = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} _UpperCamelCase : Optional[Any] = Thread(target=model.generate , kwargs=__a ) thread.start() _UpperCamelCase : Tuple = "" for new_text in streamer: streamer_text += new_text self.assertEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: _UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) _UpperCamelCase : int = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__a ) _UpperCamelCase : Union[str, Any] = -1 _UpperCamelCase : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__a ) _UpperCamelCase : Union[str, Any] = model.generate(__a , max_new_tokens=10 , do_sample=__a ) _UpperCamelCase : str = greedy_ids[:, input_ids.shape[1] :] _UpperCamelCase : Dict = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: _UpperCamelCase : Optional[int] = TextStreamer(__a , skip_prompt=__a ) model.generate(__a , max_new_tokens=10 , do_sample=__a , streamer=__a ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _UpperCamelCase : Tuple = cs.out[:-1] self.assertEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them _UpperCamelCase : Dict = AutoTokenizer.from_pretrained("distilgpt2" ) _UpperCamelCase : Optional[int] = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__a ) _UpperCamelCase : int = -1 _UpperCamelCase : Any = torch.ones((1, 5) , device=__a ).long() * model.config.bos_token_id with CaptureStdout() as cs: _UpperCamelCase : List[str] = TextStreamer(__a , skip_special_tokens=__a ) model.generate(__a , max_new_tokens=1 , do_sample=__a , streamer=__a ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _UpperCamelCase : int = cs.out[:-1] # Remove the final "\n" _UpperCamelCase : int = tokenizer(__a , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) _UpperCamelCase : Union[str, Any] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__a ) _UpperCamelCase : Optional[Any] = -1 _UpperCamelCase : Tuple = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__a ) _UpperCamelCase : Any = TextIteratorStreamer(__a , timeout=0.0_01 ) _UpperCamelCase : Optional[int] = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} _UpperCamelCase : List[Any] = Thread(target=model.generate , kwargs=__a ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__a ): _UpperCamelCase : List[str] = "" for new_text in streamer: streamer_text += new_text
310
1
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__(self : List[Any] , a__ : Optional[int] , a__ : Optional[int]=13 , a__ : List[Any]=7 , a__ : Dict=True , a__ : Optional[Any]=True , a__ : List[Any]=True , a__ : Optional[Any]=True , a__ : Optional[int]=99 , a__ : Optional[Any]=32 , a__ : List[str]=5 , a__ : Any=4 , a__ : str=37 , a__ : Optional[int]="gelu" , a__ : Optional[Any]=0.1 , a__ : Dict=0.1 , a__ : Any=512 , a__ : Union[str, Any]=16 , a__ : Any=2 , a__ : Optional[int]=0.0_2 , a__ : Optional[int]=4 , ): """simple docstring""" __snake_case = parent __snake_case = batch_size __snake_case = seq_length __snake_case = is_training __snake_case = use_attention_mask __snake_case = use_token_type_ids __snake_case = use_labels __snake_case = vocab_size __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = intermediate_size __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = max_position_embeddings __snake_case = type_vocab_size __snake_case = type_sequence_label_size __snake_case = initializer_range __snake_case = num_choices def a (self : Union[str, Any] ): """simple docstring""" __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case = None if self.use_attention_mask: __snake_case = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case = None if self.use_token_type_ids: __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a (self : List[Any] ): """simple docstring""" __snake_case = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case = config_and_inputs __snake_case = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def a (self : Dict ): """simple docstring""" __snake_case = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case = config_and_inputs __snake_case = True __snake_case = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __snake_case = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase , unittest.TestCase ): A_ : Any = True A_ : Optional[Any] = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a (self : Dict ): """simple docstring""" __snake_case = FlaxRobertaPreLayerNormModelTester(self ) @slow def a (self : List[Any] ): """simple docstring""" for model_class_name in self.all_model_classes: __snake_case = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=a__ ) __snake_case = model(np.ones((1, 1) ) ) self.assertIsNotNone(a__ ) @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def a (self : str ): """simple docstring""" __snake_case = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=a__ ) __snake_case = np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] , dtype=jnp.intaa ) __snake_case = model(a__ )[0] __snake_case = [1, 11, 5_0265] self.assertEqual(list(output.shape ) , a__ ) # compare the actual values for a slice. __snake_case = np.array( [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , a__ , atol=1E-4 ) ) @slow def a (self : Any ): """simple docstring""" __snake_case = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=a__ ) __snake_case = np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] , dtype=jnp.intaa ) __snake_case = model(a__ )[0] # compare the actual values for a slice. __snake_case = np.array( [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , a__ , atol=1E-4 ) )
24
import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) snake_case_ = logging.getLogger(__name__) @dataclass(frozen=_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ : A_ : str A_ : str A_ : Optional[str] = None A_ : Optional[str] = None A_ : Optional[str] = None @dataclass(frozen=_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ : A_ : List[int] A_ : Optional[List[int]] = None A_ : Optional[List[int]] = None A_ : Optional[Union[int, float]] = None A_ : Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): A_ : List[InputFeatures] def __init__(self : int , a__ : str , a__ : PreTrainedTokenizer , a__ : str , a__ : Optional[int] = None , a__ : List[Any]=False , a__ : bool = False , ): """simple docstring""" __snake_case = hans_processors[task]() __snake_case = os.path.join( a__ , '''cached_{}_{}_{}_{}'''.format( '''dev''' if evaluate else '''train''' , tokenizer.__class__.__name__ , str(a__ ) , a__ , ) , ) __snake_case = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) __snake_case , __snake_case = label_list[2], label_list[1] __snake_case = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __snake_case = cached_features_file + '''.lock''' with FileLock(a__ ): if os.path.exists(a__ ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) __snake_case = torch.load(a__ ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) __snake_case = ( processor.get_dev_examples(a__ ) if evaluate else processor.get_train_examples(a__ ) ) logger.info('''Training examples: %s''' , len(a__ ) ) __snake_case = hans_convert_examples_to_features(a__ , a__ , a__ , a__ ) logger.info('''Saving features into cached file %s''' , a__ ) torch.save(self.features , a__ ) def __len__(self : int ): """simple docstring""" return len(self.features ) def __getitem__(self : Dict , a__ : List[Any] ): """simple docstring""" return self.features[i] def a (self : List[Any] ): """simple docstring""" return self.label_list if is_tf_available(): import tensorflow as tf class SCREAMING_SNAKE_CASE__ : A_ : List[InputFeatures] def __init__(self : Tuple , a__ : str , a__ : PreTrainedTokenizer , a__ : str , a__ : Optional[int] = 128 , a__ : Any=False , a__ : bool = False , ): """simple docstring""" __snake_case = hans_processors[task]() __snake_case = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) __snake_case , __snake_case = label_list[2], label_list[1] __snake_case = label_list __snake_case = processor.get_dev_examples(a__ ) if evaluate else processor.get_train_examples(a__ ) __snake_case = hans_convert_examples_to_features(a__ , a__ , a__ , a__ ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='''convert examples to features''' ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' % (ex_index, len(a__ )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) __snake_case = tf.data.Dataset.from_generator( a__ , ( { '''example_id''': tf.intaa, '''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa, }, tf.intaa, ) , ( { '''example_id''': tf.TensorShape([] ), '''input_ids''': tf.TensorShape([None, None] ), '''attention_mask''': tf.TensorShape([None, None] ), '''token_type_ids''': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def a (self : Union[str, Any] ): """simple docstring""" return self.dataset def __len__(self : Dict ): """simple docstring""" return len(self.features ) def __getitem__(self : Any , a__ : Dict ): """simple docstring""" return self.features[i] def a (self : str ): """simple docstring""" return self.label_list class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def a (self : Dict , a__ : Dict ): """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(a__ , '''heuristics_train_set.txt''' ) ) , '''train''' ) def a (self : Optional[int] , a__ : Tuple ): """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(a__ , '''heuristics_evaluation_set.txt''' ) ) , '''dev''' ) def a (self : int ): """simple docstring""" return ["contradiction", "entailment", "neutral"] def a (self : Any , a__ : Optional[int] , a__ : List[Any] ): """simple docstring""" __snake_case = [] for i, line in enumerate(a__ ): if i == 0: continue __snake_case = '''%s-%s''' % (set_type, line[0]) __snake_case = line[5] __snake_case = line[6] __snake_case = line[7][2:] if line[7].startswith('''ex''' ) else line[7] __snake_case = line[0] examples.append(InputExample(guid=a__ , text_a=a__ , text_b=a__ , label=a__ , pairID=a__ ) ) return examples def lowerCamelCase__ ( snake_case_ : List[InputExample] , snake_case_ : List[str] , snake_case_ : int , snake_case_ : PreTrainedTokenizer , ) -> List[str]: __snake_case = {label: i for i, label in enumerate(snake_case_ )} __snake_case = [] for ex_index, example in tqdm.tqdm(enumerate(snake_case_ ) , desc='''convert examples to features''' ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d''' % (ex_index) ) __snake_case = tokenizer( example.text_a , example.text_b , add_special_tokens=snake_case_ , max_length=snake_case_ , padding='''max_length''' , truncation=snake_case_ , return_overflowing_tokens=snake_case_ , ) __snake_case = label_map[example.label] if example.label in label_map else 0 __snake_case = int(example.pairID ) features.append(InputFeatures(**snake_case_ , label=snake_case_ , pairID=snake_case_ ) ) for i, example in enumerate(examples[:5] ): logger.info('''*** Example ***''' ) logger.info(f"""guid: {example}""" ) logger.info(f"""features: {features[i]}""" ) return features snake_case_ = { 'hans': 3, } snake_case_ = { 'hans': HansProcessor, }
24
1
from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A ( _UpperCAmelCase ): """simple docstring""" def __init__( self : Dict,lowercase_ : Union[str, Any],lowercase_ : List[str] )-> str: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM A__ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=lowercase_,scheduler=lowercase_ ) @torch.no_grad() def __call__( self : Dict,lowercase_ : int = 1,lowercase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None,lowercase_ : float = 0.0,lowercase_ : int = 5_0,lowercase_ : Optional[bool] = None,lowercase_ : Optional[str] = "pil",lowercase_ : bool = True,)-> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' if isinstance(self.unet.config.sample_size,lowercase_ ): A__ = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: A__ = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(lowercase_,lowercase_ ) and len(lowercase_ ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(lowercase_ )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A__ = randn_tensor(lowercase_,generator=lowercase_,device=self.device,dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(lowercase_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A__ = self.unet(lowercase_,lowercase_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 A__ = self.scheduler.step( lowercase_,lowercase_,lowercase_,eta=lowercase_,use_clipped_model_output=lowercase_,generator=lowercase_ ).prev_sample A__ = (image / 2 + 0.5).clamp(0,1 ) A__ = image.cpu().permute(0,2,3,1 ).numpy() if output_type == "pil": A__ = self.numpy_to_pil(lowercase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase_ )
282
import random def _snake_case( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : str ) -> tuple: '''simple docstring''' A__ , A__ , A__ = [], [], [] for element in data: if element < pivot: less.append(SCREAMING_SNAKE_CASE__ ) elif element > pivot: greater.append(SCREAMING_SNAKE_CASE__ ) else: equal.append(SCREAMING_SNAKE_CASE__ ) return less, equal, greater def _snake_case( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int ) -> str: '''simple docstring''' if index >= len(SCREAMING_SNAKE_CASE__ ) or index < 0: return None A__ = items[random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 )] A__ = 0 A__ , A__ , A__ = _partition(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = len(SCREAMING_SNAKE_CASE__ ) A__ = len(SCREAMING_SNAKE_CASE__ ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # must be in larger else: return quick_select(SCREAMING_SNAKE_CASE__ , index - (m + count) )
282
1
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class lowercase: '''simple docstring''' def __init__( self: Tuple, a_: Union[str, Any] ): '''simple docstring''' if isinstance(__UpperCamelCase, __UpperCamelCase ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden _snake_case : Optional[Any] = deepcopy(__UpperCamelCase ) elif os.path.exists(__UpperCamelCase ): with io.open(__UpperCamelCase, """r""", encoding="""utf-8""" ) as f: _snake_case : Any = json.load(__UpperCamelCase ) else: try: _snake_case : Union[str, Any] = baseaa.urlsafe_baadecode(__UpperCamelCase ).decode("""utf-8""" ) _snake_case : str = json.loads(__UpperCamelCase ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( f"Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}" ) _snake_case : str = config self.set_stage_and_offload() def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Optional[Any] = self.get_value("""zero_optimization.stage""", -1 ) # offload _snake_case : Optional[int] = False if self.is_zeroa() or self.is_zeroa(): _snake_case : int = set(["""cpu""", """nvme"""] ) _snake_case : int = set( [ self.get_value("""zero_optimization.offload_optimizer.device""" ), self.get_value("""zero_optimization.offload_param.device""" ), ] ) if len(offload_devices & offload_devices_valid ) > 0: _snake_case : int = True def UpperCamelCase_ ( self: Dict, a_: Any ): '''simple docstring''' _snake_case : List[Any] = self.config # find the config node of interest if it exists _snake_case : int = ds_key_long.split(""".""" ) _snake_case : Union[str, Any] = nodes.pop() for node in nodes: _snake_case : List[Any] = config.get(__UpperCamelCase ) if config is None: return None, ds_key return config, ds_key def UpperCamelCase_ ( self: str, a_: Tuple, a_: Optional[Any]=None ): '''simple docstring''' _snake_case , _snake_case : Optional[Any] = self.find_config_node(__UpperCamelCase ) if config is None: return default return config.get(__UpperCamelCase, __UpperCamelCase ) def UpperCamelCase_ ( self: str, a_: List[str], a_: int=False ): '''simple docstring''' _snake_case : Tuple = self.config # find the config node of interest if it exists _snake_case : List[Any] = ds_key_long.split(""".""" ) for node in nodes: _snake_case : List[Any] = config _snake_case : List[str] = config.get(__UpperCamelCase ) if config is None: if must_exist: raise ValueError(f"Can\'t find {ds_key_long} entry in the config: {self.config}" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__UpperCamelCase ) def UpperCamelCase_ ( self: Optional[Any], a_: int ): '''simple docstring''' _snake_case : str = self.get_value(__UpperCamelCase ) return False if value is None else bool(__UpperCamelCase ) def UpperCamelCase_ ( self: int, a_: List[str] ): '''simple docstring''' _snake_case : Any = self.get_value(__UpperCamelCase ) return False if value is None else not bool(__UpperCamelCase ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' return self._stage == 2 def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' return self._stage == 3 def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' return self._offload class lowercase: '''simple docstring''' def __init__( self: Dict, a_: Any ): '''simple docstring''' _snake_case : Union[str, Any] = engine def UpperCamelCase_ ( self: str, a_: int, **a_: List[str] ): '''simple docstring''' self.engine.backward(__UpperCamelCase, **__UpperCamelCase ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class lowercase( _lowercase ): '''simple docstring''' def __init__( self: List[str], a_: Any ): '''simple docstring''' super().__init__(__UpperCamelCase, device_placement=__UpperCamelCase, scaler=__UpperCamelCase ) _snake_case : Any = hasattr(self.optimizer, """overflow""" ) def UpperCamelCase_ ( self: Any, a_: Dict=None ): '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def UpperCamelCase_ ( self: Any ): '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' if self.__has_overflow__: return self.optimizer.overflow return False class lowercase( _lowercase ): '''simple docstring''' def __init__( self: Dict, a_: Tuple, a_: List[Any] ): '''simple docstring''' super().__init__(__UpperCamelCase, __UpperCamelCase ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class lowercase: '''simple docstring''' def __init__( self: Dict, a_: Any, a_: Optional[Any]=0.001, a_: Optional[Any]=0, **a_: List[Any] ): '''simple docstring''' _snake_case : List[Any] = params _snake_case : Dict = lr _snake_case : Optional[int] = weight_decay _snake_case : str = kwargs class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: List[str], a_: int=None, a_: List[str]=0, **a_: Optional[Any] ): '''simple docstring''' _snake_case : Any = optimizer _snake_case : Optional[Any] = total_num_steps _snake_case : str = warmup_num_steps _snake_case : Any = kwargs
64
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments UpperCAmelCase = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ ( _lowercase): snake_case__ = field( default=0.0 , metadata={'''help''': '''The label smoothing epsilon to apply (if not zero).'''}) snake_case__ = field(default=_lowercase , metadata={'''help''': '''Whether to SortishSamler or not.'''}) snake_case__ = field( default=_lowercase , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''}) snake_case__ = field(default=_lowercase , metadata={'''help''': '''whether to use adafactor'''}) snake_case__ = field( default=_lowercase , metadata={'''help''': '''Encoder layer dropout probability. Goes into model.config.'''}) snake_case__ = field( default=_lowercase , metadata={'''help''': '''Decoder layer dropout probability. Goes into model.config.'''}) snake_case__ = field(default=_lowercase , metadata={'''help''': '''Dropout probability. Goes into model.config.'''}) snake_case__ = field( default=_lowercase , metadata={'''help''': '''Attention dropout probability. Goes into model.config.'''}) snake_case__ = field( default='''linear''' , metadata={'''help''': F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys())}'''} , )
256
0
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
26
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
1
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a_ ( lowerCamelCase , lowerCamelCase ): assert isinstance(lowerCamelCase , lowerCamelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCAmelCase__ = TextDatasetReader(lowerCamelCase , cache_dir=lowerCamelCase , keep_in_memory=lowerCamelCase ).read() _check_text_dataset(lowerCamelCase , lowerCamelCase ) @pytest.mark.parametrize( 'features' , [ None, {'text': 'string'}, {'text': 'int32'}, {'text': 'float32'}, ] , ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} UpperCAmelCase__ = features.copy() if features else default_expected_features UpperCAmelCase__ = ( Features({feature: Value(lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase__ = TextDatasetReader(lowerCamelCase , features=lowerCamelCase , cache_dir=lowerCamelCase ).read() _check_text_dataset(lowerCamelCase , lowerCamelCase ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} UpperCAmelCase__ = TextDatasetReader(lowerCamelCase , cache_dir=lowerCamelCase , split=lowerCamelCase ).read() _check_text_dataset(lowerCamelCase , lowerCamelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): if issubclass(lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = text_path elif issubclass(lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = [text_path] UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} UpperCAmelCase__ = TextDatasetReader(lowerCamelCase , cache_dir=lowerCamelCase ).read() _check_text_dataset(lowerCamelCase , lowerCamelCase ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=("train",) ): assert isinstance(lowerCamelCase , lowerCamelCase ) for split in splits: UpperCAmelCase__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCAmelCase__ = TextDatasetReader({'train': text_path} , cache_dir=lowerCamelCase , keep_in_memory=lowerCamelCase ).read() _check_text_datasetdict(lowerCamelCase , lowerCamelCase ) @pytest.mark.parametrize( 'features' , [ None, {'text': 'string'}, {'text': 'int32'}, {'text': 'float32'}, ] , ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = tmp_path / 'cache' # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" UpperCAmelCase__ = {'text': 'string'} UpperCAmelCase__ = features.copy() if features else default_expected_features UpperCAmelCase__ = ( Features({feature: Value(lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase__ = TextDatasetReader({'train': text_path} , features=lowerCamelCase , cache_dir=lowerCamelCase ).read() _check_text_datasetdict(lowerCamelCase , lowerCamelCase ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): if split: UpperCAmelCase__ = {split: text_path} else: UpperCAmelCase__ = 'train' UpperCAmelCase__ = {'train': text_path, 'test': text_path} UpperCAmelCase__ = tmp_path / 'cache' UpperCAmelCase__ = {'text': 'string'} UpperCAmelCase__ = TextDatasetReader(lowerCamelCase , cache_dir=lowerCamelCase ).read() _check_text_datasetdict(lowerCamelCase , lowerCamelCase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
98
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup a = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def lowercase (snake_case__ : str = "mumbai" ) -> Generator[tuple[str, str], None, None]: '''simple docstring''' lowerCAmelCase = BeautifulSoup(requests.get(url + location ).content , """html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""" , attrs={"""data-tn-component""": """organicJob"""} ): lowerCAmelCase = job.find("""a""" , attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() lowerCAmelCase = job.find("""span""" , {"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
155
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 UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {'vocab_file': 'sentencepiece.bpe.model'} UpperCamelCase__ = { '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' ), }, } UpperCamelCase__ = { 'moussaKam/mbarthez': 1_0_2_4, 'moussaKam/barthez': 1_0_2_4, 'moussaKam/barthez-orangesum-title': 1_0_2_4, } UpperCamelCase__ = '▁' class A ( UpperCAmelCase_ ): __UpperCAmelCase : Dict = VOCAB_FILES_NAMES __UpperCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : int = ['input_ids', 'attention_mask'] def __init__(self : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any]="<s>" , __UpperCAmelCase : Tuple="</s>" , __UpperCAmelCase : Tuple="</s>" , __UpperCAmelCase : int="<s>" , __UpperCAmelCase : Any="<unk>" , __UpperCAmelCase : List[str]="<pad>" , __UpperCAmelCase : int="<mask>" , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : str , ) -> None: """simple docstring""" UpperCAmelCase__ = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token UpperCAmelCase__ = {} 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 , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) UpperCAmelCase__ = vocab_file UpperCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__UpperCAmelCase ) ) UpperCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} UpperCAmelCase__ = len(self.sp_model ) - 1 UpperCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowercase_ (self : Any , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase__ = [self.cls_token_id] UpperCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowercase_ (self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] + ([0] * len(__UpperCAmelCase )) + [1] def lowercase_ (self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase__ = [self.sep_token_id] UpperCAmelCase__ = [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 lowercase_ (self : Optional[int] ) -> int: """simple docstring""" return len(self.sp_model ) def lowercase_ (self : Dict ) -> str: """simple docstring""" UpperCAmelCase__ = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowercase_ (self : int , __UpperCAmelCase : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) def lowercase_ (self : List[Any] , __UpperCAmelCase : Tuple ) -> Any: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCAmelCase__ = self.sp_model.PieceToId(__UpperCAmelCase ) return spm_id if spm_id else self.unk_token_id def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : Dict ) -> str: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__UpperCAmelCase ) def lowercase_ (self : Dict , __UpperCAmelCase : Tuple ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = [] UpperCAmelCase__ = "" UpperCAmelCase__ = 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 UpperCAmelCase__ = True UpperCAmelCase__ = [] else: current_sub_tokens.append(__UpperCAmelCase ) UpperCAmelCase__ = False out_string += self.sp_model.decode(__UpperCAmelCase ) return out_string.strip() def __getstate__(self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.__dict__.copy() UpperCAmelCase__ = None return state def __setstate__(self : int , __UpperCAmelCase : Optional[Any] ) -> int: """simple docstring""" UpperCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase__ = {} UpperCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase_ (self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase__ = 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: UpperCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,)
143
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker UpperCamelCase__ = 'CompVis/stable-diffusion-v1-1' UpperCamelCase__ = 'CompVis/stable-diffusion-v1-2' UpperCamelCase__ = 'CompVis/stable-diffusion-v1-3' UpperCamelCase__ = 'CompVis/stable-diffusion-v1-4' class A ( UpperCAmelCase_ ): def __init__(self : Union[str, Any] , __UpperCAmelCase : AutoencoderKL , __UpperCAmelCase : CLIPTextModel , __UpperCAmelCase : CLIPTokenizer , __UpperCAmelCase : UNetaDConditionModel , __UpperCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __UpperCAmelCase : StableDiffusionSafetyChecker , __UpperCAmelCase : CLIPImageProcessor , __UpperCAmelCase : bool = True , ) -> Tuple: """simple docstring""" super()._init_() UpperCAmelCase__ = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase ) UpperCAmelCase__ = StableDiffusionPipeline( vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , requires_safety_checker=__UpperCAmelCase , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def lowercase_ (self : int ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __UpperCAmelCase ) for k in self.config.keys() if not k.startswith("_" )} def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : Optional[Union[str, int]] = "auto" ) -> Optional[int]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__UpperCAmelCase ) def lowercase_ (self : int ) -> Optional[int]: """simple docstring""" self.enable_attention_slicing(__UpperCAmelCase ) @torch.no_grad() def lowercase_ (self : Optional[int] , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_0 , __UpperCAmelCase : float = 7.5 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , **__UpperCAmelCase : Any , ) -> Dict: """simple docstring""" return self.pipea( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) @torch.no_grad() def lowercase_ (self : List[str] , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_0 , __UpperCAmelCase : float = 7.5 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , **__UpperCAmelCase : Optional[Any] , ) -> Any: """simple docstring""" return self.pipea( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) @torch.no_grad() def lowercase_ (self : List[str] , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_0 , __UpperCAmelCase : float = 7.5 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , **__UpperCAmelCase : Any , ) -> Dict: """simple docstring""" return self.pipea( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) @torch.no_grad() def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_0 , __UpperCAmelCase : float = 7.5 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , **__UpperCAmelCase : Union[str, Any] , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) @torch.no_grad() def lowercase_ (self : int , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_1_2 , __UpperCAmelCase : int = 5_0 , __UpperCAmelCase : float = 7.5 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , **__UpperCAmelCase : Any , ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" self.to(__UpperCAmelCase ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase__ = self.textaimg_sda_a( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase__ = self.textaimg_sda_a( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase__ = self.textaimg_sda_a( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase__ = self.textaimg_sda_a( prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
143
1
lowerCAmelCase = [ "DownloadConfig", "DownloadManager", "DownloadMode", "StreamingDownloadManager", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
295
'''simple docstring''' def __lowerCamelCase ( A__ = 50 ) -> int: """simple docstring""" UpperCamelCase = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
28
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case : int ={'configuration_opt': ['OPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OPTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Optional[Any] =[ 'OPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OPTForCausalLM', 'OPTModel', 'OPTPreTrainedModel', 'OPTForSequenceClassification', 'OPTForQuestionAnswering', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Optional[int] =['TFOPTForCausalLM', 'TFOPTModel', 'TFOPTPreTrainedModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : int =[ 'FlaxOPTForCausalLM', 'FlaxOPTModel', 'FlaxOPTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys __snake_case : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
94
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowerCAmelCase__ ( lowerCamelCase_ : Dict ,lowerCamelCase_ : Optional[int] ,lowerCamelCase_ : List[Any]=1024 ,lowerCamelCase_ : int=1024 ,lowerCamelCase_ : Dict=False ,**lowerCamelCase_ : Tuple): '''simple docstring''' lowerCAmelCase__ : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase_) lowerCAmelCase__ : Optional[Any] = SeqaSeqDataset(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,type_path='''train''' ,**lowerCamelCase_) lowerCAmelCase__ : int = tok.pad_token_id def get_lens(lowerCamelCase_ : Tuple): lowerCAmelCase__ : Tuple = tqdm( DataLoader(lowerCamelCase_ ,batch_size=512 ,num_workers=8 ,shuffle=lowerCamelCase_ ,collate_fn=ds.collate_fn) ,desc=str(ds.len_file) ,) lowerCAmelCase__ : Tuple = [] for batch in dl: lowerCAmelCase__ : Dict = batch['''input_ids'''].ne(lowerCamelCase_).sum(1).tolist() lowerCAmelCase__ : Dict = batch['''labels'''].ne(lowerCamelCase_).sum(1).tolist() if consider_target: for src, tgt in zip(lowerCamelCase_ ,lowerCamelCase_): max_lens.append(max(lowerCamelCase_ ,lowerCamelCase_)) else: max_lens.extend(lowerCamelCase_) return max_lens lowerCAmelCase__ : str = get_lens(lowerCamelCase_) lowerCAmelCase__ : Tuple = SeqaSeqDataset(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,type_path='''val''' ,**lowerCamelCase_) lowerCAmelCase__ : Optional[int] = get_lens(lowerCamelCase_) pickle_save(lowerCamelCase_ ,train_ds.len_file) pickle_save(lowerCamelCase_ ,val_ds.len_file) if __name__ == "__main__": fire.Fire(save_len_file)
94
1
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __a = logging.getLogger(__name__) __a = tf.data.AUTOTUNE def A_ ( ): '''simple docstring''' snake_case_ :Optional[int] = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""", type=_lowercase, default="""roberta-base""", help="""The model config to use. Note that we don't copy the model's weights, only the config!""", ) parser.add_argument( """--tokenizer""", type=_lowercase, default="""unigram-tokenizer-wikitext""", help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""", ) parser.add_argument( """--per_replica_batch_size""", type=_lowercase, default=8, help="""Batch size per TPU core.""", ) parser.add_argument( """--no_tpu""", action="""store_true""", help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""", ) parser.add_argument( """--tpu_name""", type=_lowercase, help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""", default="""local""", ) parser.add_argument( """--tpu_zone""", type=_lowercase, help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""", ) parser.add_argument( """--gcp_project""", type=_lowercase, help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""", action="""store_true""", help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""", ) parser.add_argument( """--train_dataset""", type=_lowercase, help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""", ) parser.add_argument( """--shuffle_buffer_size""", type=_lowercase, default=2**18, help="""Size of the shuffle buffer (in samples)""", ) parser.add_argument( """--eval_dataset""", type=_lowercase, help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""", ) parser.add_argument( """--num_epochs""", type=_lowercase, default=1, help="""Number of epochs to train for.""", ) parser.add_argument( """--learning_rate""", type=_lowercase, default=1e-4, help="""Learning rate to use for training.""", ) parser.add_argument( """--weight_decay_rate""", type=_lowercase, default=1e-3, help="""Weight decay rate to use for training.""", ) parser.add_argument( """--max_length""", type=_lowercase, default=512, help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""", ) parser.add_argument( """--mlm_probability""", type=_lowercase, default=0.15, help="""Fraction of tokens to mask during training.""", ) parser.add_argument("""--output_dir""", type=_lowercase, required=_lowercase, help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""", type=_lowercase, help="""Model ID to upload to on the Hugging Face Hub.""" ) snake_case_ :Dict = parser.parse_args() return args def A_ ( _lowercase ): '''simple docstring''' try: if args.tpu_name: snake_case_ :List[str] = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name, zone=args.tpu_zone, project=args.gcp_project ) else: snake_case_ :List[Any] = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(_lowercase ) tf.tpu.experimental.initialize_tpu_system(_lowercase ) return tpu def A_ ( _lowercase ): '''simple docstring''' snake_case_ :Optional[int] = 0 for file in file_list: snake_case_ :List[Any] = file.split("""/""" )[-1] snake_case_ :Union[str, Any] = re.search(r"""-\d+-(\d+)\.tfrecord""", _lowercase ).group(1 ) snake_case_ :List[str] = int(_lowercase ) num_samples += sample_count return num_samples def A_ ( _lowercase, _lowercase, _lowercase, _lowercase, _lowercase, _lowercase=None ): '''simple docstring''' snake_case_ :Optional[int] = count_samples(_lowercase ) snake_case_ :Union[str, Any] = tf.data.Dataset.from_tensor_slices(_lowercase ) if shuffle: snake_case_ :List[str] = dataset.shuffle(len(_lowercase ) ) snake_case_ :Any = tf.data.TFRecordDataset(_lowercase, num_parallel_reads=_lowercase ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here snake_case_ :Optional[Any] = dataset.apply(tf.data.experimental.assert_cardinality(_lowercase ) ) snake_case_ :Any = dataset.map(_lowercase, num_parallel_calls=_lowercase ) if shuffle: assert shuffle_buffer_size is not None snake_case_ :Dict = dataset.shuffle(args.shuffle_buffer_size ) snake_case_ :Dict = dataset.batch(_lowercase, drop_remainder=_lowercase ) snake_case_ :Any = dataset.map(_lowercase, num_parallel_calls=_lowercase ) snake_case_ :Optional[int] = dataset.prefetch(_lowercase ) return dataset def A_ ( _lowercase ): '''simple docstring''' if not args.no_tpu: snake_case_ :Optional[Any] = initialize_tpu(_lowercase ) snake_case_ :Dict = tf.distribute.TPUStrategy(_lowercase ) else: snake_case_ :Tuple = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) snake_case_ :List[Any] = AutoTokenizer.from_pretrained(args.tokenizer ) snake_case_ :Any = AutoConfig.from_pretrained(args.pretrained_model_config ) snake_case_ :List[str] = tokenizer.vocab_size snake_case_ :Optional[int] = tf.io.gfile.glob(os.path.join(args.train_dataset, """*.tfrecord""" ) ) if not training_records: raise ValueError(f"""No .tfrecord files found in {args.train_dataset}.""" ) snake_case_ :Union[str, Any] = tf.io.gfile.glob(os.path.join(args.eval_dataset, """*.tfrecord""" ) ) if not eval_records: raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}.""" ) snake_case_ :Optional[Any] = count_samples(_lowercase ) snake_case_ :Union[str, Any] = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) snake_case_ :List[str] = steps_per_epoch * args.num_epochs with strategy.scope(): snake_case_ :List[str] = TFAutoModelForMaskedLM.from_config(_lowercase ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built snake_case_, snake_case_ :Optional[Any] = create_optimizer( num_train_steps=_lowercase, num_warmup_steps=total_train_steps // 20, init_lr=args.learning_rate, weight_decay_rate=args.weight_decay_rate, ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_lowercase, metrics=["""accuracy"""] ) def decode_fn(_lowercase ): snake_case_ :Tuple = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa, shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa, shape=(args.max_length,) ), } return tf.io.parse_single_example(_lowercase, _lowercase ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. snake_case_ :Any = DataCollatorForLanguageModeling( tokenizer=_lowercase, mlm_probability=args.mlm_probability, mlm=_lowercase, return_tensors="""tf""" ) def mask_with_collator(_lowercase ): # TF really needs an isin() function snake_case_ :List[str] = ( ~tf.cast(batch["""attention_mask"""], tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) snake_case_, snake_case_ :Union[str, Any] = data_collator.tf_mask_tokens( batch["""input_ids"""], vocab_size=len(_lowercase ), mask_token_id=tokenizer.mask_token_id, special_tokens_mask=_lowercase, ) return batch snake_case_ :Optional[Any] = args.per_replica_batch_size * strategy.num_replicas_in_sync snake_case_ :Union[str, Any] = prepare_dataset( _lowercase, decode_fn=_lowercase, mask_fn=_lowercase, batch_size=_lowercase, shuffle=_lowercase, shuffle_buffer_size=args.shuffle_buffer_size, ) snake_case_ :Optional[Any] = prepare_dataset( _lowercase, decode_fn=_lowercase, mask_fn=_lowercase, batch_size=_lowercase, shuffle=_lowercase, ) snake_case_ :List[Any] = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir, hub_model_id=args.hub_model_id, tokenizer=_lowercase ) ) model.fit( _lowercase, validation_data=_lowercase, epochs=args.num_epochs, callbacks=_lowercase, ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __a = parse_args() main(args)
66
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class a ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self: str ): """simple docstring""" A__ = get_activation("""swish""" ) self.assertIsInstance(UpperCamelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Any ): """simple docstring""" A__ = get_activation("""silu""" ) self.assertIsInstance(UpperCamelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Optional[int] ): """simple docstring""" A__ = get_activation("""mish""" ) self.assertIsInstance(UpperCamelCase , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Any ): """simple docstring""" A__ = get_activation("""gelu""" ) self.assertIsInstance(UpperCamelCase , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
335
0
"""simple docstring""" from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
11
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase_ = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n" class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-question-answering''' ) self.tool.setup() __a = load_tool('''text-question-answering''' , remote=_a ) def __UpperCAmelCase ( self ): __a = self.tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(_a , '''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' ) def __UpperCAmelCase ( self ): __a = self.remote_tool(text=_a , question='''What did Hugging Face do in April 2021?''' ) self.assertEqual(_a , '''launched the BigScience Research Workshop''' )
11
1
'''simple docstring''' import json import sys def lowerCAmelCase (__A , __A): """simple docstring""" with open(__A , encoding='''utf-8''') as f: _a = json.load(__A) _a = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' '''] for benchmark_name in sorted(__A): _a = results[benchmark_name] _a = benchmark_name.split('''/''')[-1] output_md.append(F'''### Benchmark: {benchmark_file_name}''') _a = '''| metric |''' _a = '''|--------|''' _a = '''| new / old (diff) |''' for metric_name in sorted(__A): _a = benchmark_res[metric_name] _a = metric_vals['''new'''] _a = metric_vals.get('''old''' , __A) _a = metric_vals.get('''diff''' , __A) _a = F''' {new_val:f}''' if isinstance(__A , (int, float)) else '''None''' if old_val is not None: val_str += F''' / {old_val:f}''' if isinstance(__A , (int, float)) else "None" if dif_val is not None: val_str += F''' ({dif_val:f})''' if isinstance(__A , (int, float)) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append('''</details>''') with open(__A , '''w''' , encoding='''utf-8''') as f: f.writelines('''\n'''.join(__A)) if __name__ == "__main__": lowercase_ = sys.argv[1] lowercase_ = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
211
'''simple docstring''' import random def lowerCAmelCase (__A): """simple docstring""" _a = num - 1 _a = 0 while s % 2 == 0: _a = s // 2 t += 1 for _ in range(5): _a = random.randrange(2 , num - 1) _a = pow(__A , __A , __A) if v != 1: _a = 0 while v != (num - 1): if i == t - 1: return False else: _a = i + 1 _a = (v**2) % num return True def lowerCAmelCase (__A): """simple docstring""" if num < 2: return False _a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__A) def lowerCAmelCase (__A = 1_024): """simple docstring""" while True: _a = random.randrange(2 ** (keysize - 1) , 2 ** (keysize)) if is_prime_low_num(__A): return num if __name__ == "__main__": lowercase_ = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
211
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase__ = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=8 ): """simple docstring""" UpperCamelCase = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 UpperCamelCase = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=512 ): """simple docstring""" UpperCamelCase = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) UpperCamelCase = np.array(pil_image.convert("RGB" ) ) UpperCamelCase = arr.astype(np.floataa ) / 1_27.5 - 1 UpperCamelCase = np.transpose(_SCREAMING_SNAKE_CASE , [2, 0, 1] ) UpperCamelCase = torch.from_numpy(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) return image class _lowerCamelCase ( _lowercase ): def __init__(self , __a , __a , __a , ) -> List[Any]: super().__init__() self.register_modules( unet=__a , scheduler=__a , movq=__a , ) UpperCamelCase = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_ (self , __a , __a , __a ) -> Optional[Any]: # get the original timestep using init_timestep UpperCamelCase = min(int(num_inference_steps * strength ) , __a ) UpperCamelCase = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def snake_case_ (self , __a , __a , __a , __a , __a , __a , __a=None ) -> str: if not isinstance(__a , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__a )}" ) UpperCamelCase = image.to(device=__a , dtype=__a ) UpperCamelCase = batch_size * num_images_per_prompt if image.shape[1] == 4: UpperCamelCase = image else: if isinstance(__a , __a ) and len(__a ) != batch_size: raise ValueError( F"You have passed a list of generators of length {len(__a )}, but requested an effective batch" F" size of {batch_size}. Make sure the batch size matches the length of the generators." ) elif isinstance(__a , __a ): UpperCamelCase = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__a ) ] UpperCamelCase = torch.cat(__a , dim=0 ) else: UpperCamelCase = self.movq.encode(__a ).latent_dist.sample(__a ) UpperCamelCase = self.movq.config.scaling_factor * init_latents UpperCamelCase = torch.cat([init_latents] , dim=0 ) UpperCamelCase = init_latents.shape UpperCamelCase = randn_tensor(__a , generator=__a , device=__a , dtype=__a ) # get latents UpperCamelCase = self.scheduler.add_noise(__a , __a , __a ) UpperCamelCase = init_latents return latents def snake_case_ (self , __a=0 ) -> List[Any]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCamelCase = torch.device(F"cuda:{gpu_id}" ) UpperCamelCase = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) def snake_case_ (self , __a=0 ) -> List[Any]: if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) UpperCamelCase = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=__a ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) UpperCamelCase = None for cpu_offloaded_model in [self.unet, self.movq]: UpperCamelCase , UpperCamelCase = cpu_offload_with_hook(__a , __a , prev_module_hook=__a ) # We'll offload the last model manually. UpperCamelCase = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_ (self ) -> Dict: if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(__a ) def __call__(self , __a , __a , __a , __a = 5_12 , __a = 5_12 , __a = 1_00 , __a = 4.0 , __a = 0.3 , __a = 1 , __a = None , __a = "pil" , __a = True , ) -> Any: UpperCamelCase = self._execution_device UpperCamelCase = guidance_scale > 1.0 if isinstance(__a , __a ): UpperCamelCase = torch.cat(__a , dim=0 ) UpperCamelCase = image_embeds.shape[0] if isinstance(__a , __a ): UpperCamelCase = torch.cat(__a , dim=0 ) if do_classifier_free_guidance: UpperCamelCase = image_embeds.repeat_interleave(__a , dim=0 ) UpperCamelCase = negative_image_embeds.repeat_interleave(__a , dim=0 ) UpperCamelCase = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__a ) if not isinstance(__a , __a ): UpperCamelCase = [image] if not all(isinstance(__a , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"Input is in incorrect format: {[type(__a ) for i in image]}. Currently, we only support PIL image and pytorch tensor" ) UpperCamelCase = torch.cat([prepare_image(__a , __a , __a ) for i in image] , dim=0 ) UpperCamelCase = image.to(dtype=image_embeds.dtype , device=__a ) UpperCamelCase = self.movq.encode(__a )["latents"] UpperCamelCase = latents.repeat_interleave(__a , dim=0 ) self.scheduler.set_timesteps(__a , device=__a ) UpperCamelCase , UpperCamelCase = self.get_timesteps(__a , __a , __a ) UpperCamelCase = timesteps[:1].repeat(batch_size * num_images_per_prompt ) UpperCamelCase , UpperCamelCase = downscale_height_and_width(__a , __a , self.movq_scale_factor ) UpperCamelCase = self.prepare_latents( __a , __a , __a , __a , image_embeds.dtype , __a , __a ) for i, t in enumerate(self.progress_bar(__a ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase = {"image_embeds": image_embeds} UpperCamelCase = self.unet( sample=__a , timestep=__a , encoder_hidden_states=__a , added_cond_kwargs=__a , return_dict=__a , )[0] if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) UpperCamelCase , UpperCamelCase = noise_pred.chunk(2 ) UpperCamelCase , UpperCamelCase = variance_pred.chunk(2 ) UpperCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) UpperCamelCase = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): UpperCamelCase , UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase = self.scheduler.step( __a , __a , __a , generator=__a , )[0] # post-processing UpperCamelCase = self.movq.decode(__a , force_not_quantize=__a )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: UpperCamelCase = image * 0.5 + 0.5 UpperCamelCase = image.clamp(0 , 1 ) UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCamelCase = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
244
"""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.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _lowerCamelCase ( _lowercase ): UpperCAmelCase_ = "facebook/bart-large-mnli" UpperCAmelCase_ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) UpperCAmelCase_ = "text_classifier" UpperCAmelCase_ = AutoTokenizer UpperCAmelCase_ = AutoModelForSequenceClassification UpperCAmelCase_ = ["text", ["text"]] UpperCAmelCase_ = ["text"] def snake_case_ (self ) -> List[Any]: super().setup() UpperCamelCase = self.model.config UpperCamelCase = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): UpperCamelCase = int(__a ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def snake_case_ (self , __a , __a ) -> List[Any]: UpperCamelCase = labels return self.pre_processor( [text] * len(__a ) , [F"This example is {label}" for label in labels] , return_tensors="pt" , padding="max_length" , ) def snake_case_ (self , __a ) -> int: UpperCamelCase = outputs.logits UpperCamelCase = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
244
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _lowerCamelCase ( unittest.TestCase ): _lowerCamelCase :Any = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowerCamelCase :Optional[int] = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _lowerCAmelCase ( self : Optional[int] , UpperCamelCase : str , UpperCamelCase : int , UpperCamelCase : Tuple ) -> int: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = TextaTextGenerationPipeline(model=a_ , tokenizer=a_ ) return generator, ["Something to write", "Something else"] def _lowerCAmelCase ( self : Tuple , UpperCamelCase : List[str] , UpperCamelCase : List[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = generator("""Something there""" ) self.assertEqual(a_ , [{"""generated_text""": ANY(a_ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) ) lowerCAmelCase__ : List[Any] = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=a_ ) self.assertEqual( a_ , [ [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], ] , ) lowerCAmelCase__ : Optional[int] = generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=a_ ) self.assertEqual( a_ , [ [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], [{"""generated_text""": ANY(a_ )}, {"""generated_text""": ANY(a_ )}], ] , ) with self.assertRaises(a_ ): generator(4 ) @require_torch def _lowerCAmelCase ( self : str ) -> List[str]: """simple docstring""" lowerCAmelCase__ : Any = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""" ) # do_sample=False necessary for reproducibility lowerCAmelCase__ : int = generator("""Something there""" , do_sample=a_ ) self.assertEqual(a_ , [{"""generated_text""": """"""}] ) lowerCAmelCase__ : Optional[int] = 3 lowerCAmelCase__ : int = generator( """Something there""" , num_return_sequences=a_ , num_beams=a_ , ) lowerCAmelCase__ : Dict = [ {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': ''''''}, ] self.assertEqual(a_ , a_ ) lowerCAmelCase__ : List[Any] = generator("""This is a test""" , do_sample=a_ , num_return_sequences=2 , return_tensors=a_ ) self.assertEqual( a_ , [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ] , ) lowerCAmelCase__ : Dict = generator.model.config.eos_token_id lowerCAmelCase__ : Any = '''<pad>''' lowerCAmelCase__ : Tuple = generator( ["""This is a test""", """This is a second test"""] , do_sample=a_ , num_return_sequences=2 , batch_size=2 , return_tensors=a_ , ) self.assertEqual( a_ , [ [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], [ {"""generated_token_ids""": ANY(torch.Tensor )}, {"""generated_token_ids""": ANY(torch.Tensor )}, ], ] , ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" lowerCAmelCase__ : Optional[int] = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""" ) # do_sample=False necessary for reproducibility lowerCAmelCase__ : Union[str, Any] = generator("""Something there""" , do_sample=a_ ) self.assertEqual(a_ , [{"""generated_text""": """"""}] )
242
"""simple docstring""" from sklearn.metrics import recall_score import datasets SCREAMING_SNAKE_CASE : Dict = """ Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. """ SCREAMING_SNAKE_CASE : Any = """ Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {'recall': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {'recall': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric('recall') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {'recall': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric('recall') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'recall': array([1., 0., 0.])} """ SCREAMING_SNAKE_CASE : Tuple = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html'''] , ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_=None , a_=1 , a_="binary" , a_=None , a_="warn" , ): '''simple docstring''' __snake_case : Any = recall_score( a_ , a_ , labels=a_ , pos_label=a_ , average=a_ , sample_weight=a_ , zero_division=a_ , ) return {"recall": float(a_ ) if score.size == 1 else score}
102
0
'''simple docstring''' from __future__ import annotations def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): if b == 0: return (1, 0) (_UpperCamelCase) : Dict = extended_euclid(UpperCAmelCase_ , a % b ) _UpperCamelCase : List[Any] = a // b return (y, x - k * y) def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): (_UpperCamelCase) : Optional[int] = extended_euclid(UpperCAmelCase_ , UpperCAmelCase_ ) _UpperCamelCase : Optional[Any] = na * na _UpperCamelCase : Optional[int] = ra * x * na + ra * y * na return (n % m + m) % m def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): (_UpperCamelCase) : int = extended_euclid(UpperCAmelCase_ , UpperCAmelCase_ ) if b < 0: _UpperCamelCase : str = (b % n + n) % n return b def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : List[str] = invert_modulo(UpperCAmelCase_ , UpperCAmelCase_ ), invert_modulo(UpperCAmelCase_ , UpperCAmelCase_ ) _UpperCamelCase : Any = na * na _UpperCamelCase : List[str] = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='chinese_remainder_theorem', verbose=True) testmod(name='chinese_remainder_theorem2', verbose=True) testmod(name='invert_modulo', verbose=True) testmod(name='extended_euclid', verbose=True)
360
'''simple docstring''' from __future__ import annotations import numpy as np def A__ ( UpperCAmelCase_ ): _UpperCamelCase , _UpperCamelCase : Optional[int] = np.shape(UpperCAmelCase_ ) if rows != columns: _UpperCamelCase : Union[str, Any] = ( '\'table\' has to be of square shaped array but got a ' f'{rows}x{columns} array:\n{table}' ) raise ValueError(UpperCAmelCase_ ) _UpperCamelCase : Optional[Any] = np.zeros((rows, columns) ) _UpperCamelCase : Tuple = np.zeros((rows, columns) ) for i in range(UpperCAmelCase_ ): for j in range(UpperCAmelCase_ ): _UpperCamelCase : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(UpperCAmelCase_ ) ) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists' ) _UpperCamelCase : Optional[Any] = (table[i][j] - total) / upper[j][j] _UpperCamelCase : int = 1 for j in range(UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Optional[int] = sum(lower[i][k] * upper[k][j] for k in range(UpperCAmelCase_ ) ) _UpperCamelCase : Tuple = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
236
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Optional[int] = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class lowercase__ ( snake_case__ ): _UpperCAmelCase :Tuple = "beit" def __init__( self : Optional[Any] , snake_case__ : int=8192 , snake_case__ : List[str]=768 , snake_case__ : int=12 , snake_case__ : Tuple=12 , snake_case__ : Optional[int]=3072 , snake_case__ : List[Any]="gelu" , snake_case__ : Tuple=0.0 , snake_case__ : List[str]=0.0 , snake_case__ : str=0.02 , snake_case__ : Dict=1E-12 , snake_case__ : Tuple=224 , snake_case__ : Union[str, Any]=16 , snake_case__ : List[Any]=3 , snake_case__ : str=False , snake_case__ : Any=False , snake_case__ : int=False , snake_case__ : Optional[Any]=False , snake_case__ : Optional[Any]=0.1 , snake_case__ : Union[str, Any]=0.1 , snake_case__ : Optional[int]=True , snake_case__ : int=[3, 5, 7, 11] , snake_case__ : List[str]=[1, 2, 3, 6] , snake_case__ : Tuple=True , snake_case__ : Optional[int]=0.4 , snake_case__ : Dict=256 , snake_case__ : List[str]=1 , snake_case__ : Optional[int]=False , snake_case__ : int=255 , **snake_case__ : Tuple , ): super().__init__(**snake_case__ ) lowerCamelCase_ : Optional[int] =vocab_size lowerCamelCase_ : List[str] =hidden_size lowerCamelCase_ : List[Any] =num_hidden_layers lowerCamelCase_ : Optional[int] =num_attention_heads lowerCamelCase_ : Optional[Any] =intermediate_size lowerCamelCase_ : List[Any] =hidden_act lowerCamelCase_ : Optional[int] =hidden_dropout_prob lowerCamelCase_ : List[Any] =attention_probs_dropout_prob lowerCamelCase_ : List[str] =initializer_range lowerCamelCase_ : Optional[int] =layer_norm_eps lowerCamelCase_ : Optional[int] =image_size lowerCamelCase_ : int =patch_size lowerCamelCase_ : str =num_channels lowerCamelCase_ : List[str] =use_mask_token lowerCamelCase_ : Tuple =use_absolute_position_embeddings lowerCamelCase_ : Any =use_relative_position_bias lowerCamelCase_ : Dict =use_shared_relative_position_bias lowerCamelCase_ : Dict =layer_scale_init_value lowerCamelCase_ : Tuple =drop_path_rate lowerCamelCase_ : Tuple =use_mean_pooling # decode head attributes (semantic segmentation) lowerCamelCase_ : Union[str, Any] =out_indices lowerCamelCase_ : Any =pool_scales # auxiliary head attributes (semantic segmentation) lowerCamelCase_ : List[Any] =use_auxiliary_head lowerCamelCase_ : List[Any] =auxiliary_loss_weight lowerCamelCase_ : Optional[Any] =auxiliary_channels lowerCamelCase_ : Optional[int] =auxiliary_num_convs lowerCamelCase_ : Union[str, Any] =auxiliary_concat_input lowerCamelCase_ : Any =semantic_loss_ignore_index class lowercase__ ( snake_case__ ): _UpperCAmelCase :Optional[Any] = version.parse("1.11" ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCAmelCase__ ( self : Optional[int] ): return 1E-4
144
"""simple docstring""" import math def _snake_case ( lowerCamelCase__ : list , lowerCamelCase__ : int ) -> int: lowerCamelCase_ : int =len(lowerCamelCase__ ) lowerCamelCase_ : List[Any] =int(math.floor(math.sqrt(lowerCamelCase__ ) ) ) lowerCamelCase_ : List[Any] =0 while arr[min(lowerCamelCase__ , lowerCamelCase__ ) - 1] < x: lowerCamelCase_ : str =step step += int(math.floor(math.sqrt(lowerCamelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: lowerCamelCase_ : Dict =prev + 1 if prev == min(lowerCamelCase__ , lowerCamelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": A__ : List[Any] = input('Enter numbers separated by a comma:\n').strip() A__ : Optional[Any] = [int(item) for item in user_input.split(',')] A__ : List[str] = int(input('Enter the number to be searched:\n')) A__ : Any = jump_search(arr, x) if res == -1: print('Number not found!') else: print(f'Number {x} is at index {res}')
144
1
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE = get_tests_dir("""fixtures/test_sentencepiece_with_bytefallback.model""") @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( snake_case_ , unittest.TestCase ): __magic_name__: Any = GPTSwaTokenizer __magic_name__: List[str] = False __magic_name__: Any = True __magic_name__: Union[str, Any] = False def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Optional[Any] = GPTSwaTokenizer(_A , eos_token='<unk>' , bos_token='<unk>' , pad_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self : int , _A : Any ) -> str: """simple docstring""" snake_case_ : Tuple = 'This is a test' snake_case_ : Union[str, Any] = 'This is a test' return input_text, output_text def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" snake_case_ : Optional[int] = '<s>' snake_case_ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: """simple docstring""" snake_case_ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(_A ) , 2000 ) def UpperCAmelCase_ ( self : int ) -> int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: """simple docstring""" snake_case_ : Optional[Any] = GPTSwaTokenizer(_A ) snake_case_ : Union[str, Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [465, 287, 265, 631, 842] ) snake_case_ : Optional[int] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) # fmt: off self.assertListEqual( _A , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] , ) # fmt: on snake_case_ : Optional[int] = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) snake_case_ : List[str] = tokenizer.convert_ids_to_tokens(_A ) # fmt: off self.assertListEqual( _A , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] ) # fmt: on def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" snake_case_ : Optional[Any] = GPTSwaTokenizer(_A ) snake_case_ : int = ['This is a test', 'I was born in 92000, and this is falsé.'] snake_case_ : int = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_A , _A ): self.assertListEqual(tokenizer.encode_fast(_A ) , _A ) # Test that decode_fast returns the input text for text, token_ids in zip(_A , _A ): self.assertEqual(tokenizer.decode_fast(_A ) , _A ) @slow def UpperCAmelCase_ ( self : Any ) -> str: """simple docstring""" snake_case_ : Optional[int] = [ '<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')', 'Hey there, how are you doing this fine day?', 'This is a text with a trailing spaces followed by a dot .', 'Häj sväjs lillebrör! =)', 'Det är inget fel på Mr. Cool', ] # fmt: off snake_case_ : Dict = {'input_ids': [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='AI-Sweden/gpt-sw3-126m' , sequences=_A , )
88
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE_ ( snake_case_ ): __magic_name__: Optional[Any] = ["image_processor", "tokenizer"] __magic_name__: Optional[Any] = "LayoutLMv3ImageProcessor" __magic_name__: str = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast") def __init__( self : int , _A : List[str]=None , _A : Dict=None , **_A : int ) -> List[str]: """simple docstring""" snake_case_ : Any = 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 , ) snake_case_ : Any = kwargs.pop('feature_extractor' ) snake_case_ : Optional[int] = 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 : List[str] , _A : Optional[Any] , _A : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _A : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , _A : Union[List[List[int]], List[List[List[int]]]] = None , _A : Optional[Union[List[int], List[List[int]]]] = None , _A : bool = True , _A : Union[bool, str, PaddingStrategy] = False , _A : Union[bool, str, TruncationStrategy] = None , _A : Optional[int] = None , _A : int = 0 , _A : Optional[int] = None , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = True , _A : Optional[Union[str, TensorType]] = None , **_A : str , ) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' ) # first, apply the image processor snake_case_ : str = self.image_processor(images=_A , return_tensors=_A ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_A , _A ): snake_case_ : List[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) snake_case_ : str = features['words'] snake_case_ : Optional[int] = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_token_type_ids=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , ) # add pixel values snake_case_ : List[str] = features.pop('pixel_values' ) if return_overflowing_tokens is True: snake_case_ : Dict = self.get_overflowing_images(_A , encoded_inputs['overflow_to_sample_mapping'] ) snake_case_ : Optional[Any] = images return encoded_inputs def UpperCAmelCase_ ( self : Dict , _A : Tuple , _A : Dict ) -> Union[str, Any]: """simple docstring""" snake_case_ : List[str] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_A ) != len(_A ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F""" {len(_A )} and {len(_A )}""" ) return images_with_overflow def UpperCAmelCase_ ( self : Optional[Any] , *_A : Optional[Any] , **_A : List[Any] ) -> List[str]: """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A ) def UpperCAmelCase_ ( self : Union[str, Any] , *_A : Dict , **_A : str ) -> Any: """simple docstring""" return self.tokenizer.decode(*_A , **_A ) @property def UpperCAmelCase_ ( self : Optional[int] ) -> int: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def UpperCAmelCase_ ( self : Any ) -> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _A , ) return self.image_processor_class @property def UpperCAmelCase_ ( self : List[Any] ) -> int: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _A , ) return self.image_processor
88
1
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE_ : def __init__( self : Tuple , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int]=13 , lowerCamelCase_ : Union[str, Any]=3 , lowerCamelCase_ : List[str]=True , lowerCamelCase_ : Dict=True , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : Union[str, Any]=0.1 , lowerCamelCase_ : Optional[Any]=224 , lowerCamelCase_ : List[Any]=1000 , lowerCamelCase_ : Dict=[3, 3, 6, 4] , lowerCamelCase_ : Optional[int]=[48, 56, 112, 220] , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = num_labels UpperCamelCase = image_size UpperCamelCase = layer_depths UpperCamelCase = embed_dims def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCamelCase_ , layer_scale_init_value=1E-5 , ) def lowerCamelCase_ ( self : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple ): """simple docstring""" UpperCamelCase = SwiftFormerModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCamelCase = model(lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict ): """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = SwiftFormerForImageClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCamelCase = model(lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) UpperCamelCase = SwiftFormerForImageClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = model(lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) = self.prepare_config_and_inputs() UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () __lowerCAmelCase = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = SwiftFormerModelTester(self ) UpperCamelCase = ConfigTester( self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" pass def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase_ , nn.Linear ) ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) @slow def lowerCamelCase_ ( self : Tuple ): """simple docstring""" for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = SwiftFormerModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" pass def lowerCamelCase_ ( self : List[str] ): """simple docstring""" def check_hidden_states_output(lowerCamelCase_ : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ): UpperCamelCase = model_class(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 8 self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCamelCase_ ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): """simple docstring""" def _config_zero_init(lowerCamelCase_ : List[Any] ): UpperCamelCase = copy.deepcopy(lowerCamelCase_ ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCamelCase_ , lowerCamelCase_ , 1E-10 ) if isinstance(getattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) , lowerCamelCase_ ): UpperCamelCase = _config_zero_init(getattr(lowerCamelCase_ , lowerCamelCase_ ) ) setattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return configs_no_init UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = _config_zero_init(lowerCamelCase_ ) for model_class in self.all_model_classes: UpperCamelCase = model_class(config=lowerCamelCase_ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self : Any ): """simple docstring""" pass def lowercase( ) -> Any: '''simple docstring''' UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(lowerCamelCase_ ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=lowerCamelCase_ , return_tensors="""pt""" ).to(lowerCamelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**lowerCamelCase_ ) # verify the logits UpperCamelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) UpperCamelCase = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase_ , atol=1E-4 ) )
343
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def __init__( self : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[int]=13 , lowerCamelCase_ : Union[str, Any]=30 , lowerCamelCase_ : str=2 , lowerCamelCase_ : Optional[int]=3 , lowerCamelCase_ : Union[str, Any]=True , lowerCamelCase_ : List[str]=True , lowerCamelCase_ : List[str]=32 , lowerCamelCase_ : Union[str, Any]=5 , lowerCamelCase_ : Optional[Any]=4 , lowerCamelCase_ : Any=37 , lowerCamelCase_ : Optional[Any]="gelu" , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : Union[str, Any]=10 , lowerCamelCase_ : Optional[Any]=0.0_2 , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase = (image_size // patch_size) ** 2 UpperCamelCase = num_patches + 1 def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase_ , initializer_range=self.initializer_range , ) return config, pixel_values def lowerCamelCase_ ( self : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple ): """simple docstring""" UpperCamelCase = FlaxViTModel(config=lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase = (self.image_size, self.image_size) UpperCamelCase = (self.patch_size, self.patch_size) UpperCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[Any] ): """simple docstring""" UpperCamelCase = self.type_sequence_label_size UpperCamelCase = FlaxViTForImageClassification(config=lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase = 1 UpperCamelCase = FlaxViTForImageClassification(lowerCamelCase_ ) UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase = model(lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ) = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = FlaxViTModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = model_class(lowerCamelCase_ ) @jax.jit def model_jitted(lowerCamelCase_ : Any , **lowerCamelCase_ : Any ): return model(pixel_values=lowerCamelCase_ , **lowerCamelCase_ ) with self.subTest("""JIT Enabled""" ): UpperCamelCase = model_jitted(**lowerCamelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase = model_jitted(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) for jitted_output, output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained("""google/vit-base-patch16-224""" ) UpperCamelCase = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(lowerCamelCase_ )
343
1
import math def lowerCAmelCase__ ( ) -> None: lowerCAmelCase__ : Optional[Any] = input('Enter message: ' ) lowerCAmelCase__ : Dict = int(input(F'''Enter key [2-{len(SCREAMING_SNAKE_CASE_ ) - 1}]: ''' ) ) lowerCAmelCase__ : Optional[Any] = input('Encryption/Decryption [e/d]: ' ) if mode.lower().startswith('e' ): lowerCAmelCase__ : Union[str, Any] = encrypt_message(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif mode.lower().startswith('d' ): lowerCAmelCase__ : List[Any] = decrypt_message(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'''Output:\n{text + "|"}''' ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: lowerCAmelCase__ : Optional[int] = [''] * key for col in range(SCREAMING_SNAKE_CASE_ ): lowerCAmelCase__ : Optional[int] = col while pointer < len(SCREAMING_SNAKE_CASE_ ): cipher_text[col] += message[pointer] pointer += key return "".join(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: lowerCAmelCase__ : str = math.ceil(len(SCREAMING_SNAKE_CASE_ ) / key ) lowerCAmelCase__ : Optional[int] = key lowerCAmelCase__ : List[str] = (num_cols * num_rows) - len(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Dict = [''] * num_cols lowerCAmelCase__ : int = 0 lowerCAmelCase__ : Optional[Any] = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowerCAmelCase__ : List[Any] = 0 row += 1 return "".join(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
307
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 A__ ( __magic_name__ , unittest.TestCase ): lowercase = DanceDiffusionPipeline lowercase = UNCONDITIONAL_AUDIO_GENERATION_PARAMS lowercase = PipelineTesterMixin.required_optional_params - { 'callback', 'latents', 'callback_steps', 'output_type', 'num_images_per_prompt', } lowercase = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS lowercase = False lowercase = False def _lowerCamelCase ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ : Optional[int] = UNetaDModel( block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=16_000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=a , use_timestep_embedding=a , time_embedding_type='fourier' , mid_block_type='UNetMidBlock1D' , down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D') , up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip') , ) lowerCAmelCase__ : Tuple = IPNDMScheduler() lowerCAmelCase__ : str = { 'unet': unet, 'scheduler': scheduler, } return components def _lowerCamelCase ( self : int , a : Dict , a : List[str]=0 ): '''simple docstring''' if str(a ).startswith('mps' ): lowerCAmelCase__ : Union[str, Any] = torch.manual_seed(a ) else: lowerCAmelCase__ : Optional[Any] = torch.Generator(device=a ).manual_seed(a ) lowerCAmelCase__ : Optional[Any] = { 'batch_size': 1, 'generator': generator, 'num_inference_steps': 4, } return inputs def _lowerCamelCase ( self : Optional[Any] ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : int = self.get_dummy_components() lowerCAmelCase__ : List[str] = DanceDiffusionPipeline(**a ) lowerCAmelCase__ : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) lowerCAmelCase__ : List[str] = self.get_dummy_inputs(a ) lowerCAmelCase__ : List[Any] = pipe(**a ) lowerCAmelCase__ : List[str] = output.audios lowerCAmelCase__ : Optional[Any] = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) lowerCAmelCase__ : List[Any] = 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 _lowerCamelCase ( self : str ): '''simple docstring''' return super().test_save_load_local() @skip_mps def _lowerCamelCase ( self : Tuple ): '''simple docstring''' return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) @skip_mps def _lowerCamelCase ( self : List[str] ): '''simple docstring''' return super().test_save_load_optional_components() @skip_mps def _lowerCamelCase ( self : Tuple ): '''simple docstring''' return super().test_attention_slicing_forward_pass() def _lowerCamelCase ( self : List[str] ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def _lowerCamelCase ( self : Dict ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCAmelCase__ : Tuple = torch_device lowerCAmelCase__ : List[str] = DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k' ) lowerCAmelCase__ : List[str] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) lowerCAmelCase__ : Optional[int] = torch.manual_seed(0 ) lowerCAmelCase__ : Optional[int] = pipe(generator=a , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) lowerCAmelCase__ : int = output.audios lowerCAmelCase__ : List[Any] = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCAmelCase__ : Dict = 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 _lowerCamelCase ( self : Tuple ): '''simple docstring''' lowerCAmelCase__ : str = torch_device lowerCAmelCase__ : List[Any] = DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k' , torch_dtype=torch.floataa ) lowerCAmelCase__ : Optional[int] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) lowerCAmelCase__ : str = torch.manual_seed(0 ) lowerCAmelCase__ : Optional[int] = pipe(generator=a , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) lowerCAmelCase__ : str = output.audios lowerCAmelCase__ : Tuple = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCAmelCase__ : int = 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
307
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } _snake_case = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } _snake_case = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = PRETRAINED_INIT_CONFIGURATION _a = ["input_ids", "attention_mask"] _a = DistilBertTokenizer def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ) -> Tuple: 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 : List[Any] = 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 : str = getattr(_a , normalizer_state.pop("""type""" ) ) _A : str = do_lower_case _A : Any = strip_accents _A : Optional[int] = tokenize_chinese_chars _A : int = normalizer_class(**_a ) _A : str = do_lower_case def a__ ( self , _a , _a=None ) -> Dict: _A : Tuple = [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 a__ ( self , _a , _a = None ) -> List[int]: _A : Dict = [self.sep_token_id] _A : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a__ ( self , _a , _a = None ) -> Tuple[str]: _A : Optional[Any] = self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
26
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class lowercase ( unittest.TestCase ): @slow def a__ ( self ) -> Any: _A : Tuple = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) _A : List[Any] = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" _A : List[str] = model(_a )["""last_hidden_state"""] _A : Union[str, Any] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. _A : List[Any] = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
26
1
from ...configuration_utils import PretrainedConfig _A = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class UpperCAmelCase__ ( __UpperCamelCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "tapas" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=1024 , A_=[3, 256, 256, 2, 256, 256, 10] , A_=0.02 , A_=1E-12 , A_=0 , A_=10.0 , A_=0 , A_=1.0 , A_=None , A_=1.0 , A_=False , A_=None , A_=1.0 , A_=1.0 , A_=False , A_=False , A_="ratio" , A_=None , A_=None , A_=64 , A_=32 , A_=False , A_=True , A_=False , A_=False , A_=True , A_=False , A_=None , A_=None , **A_ , ) -> str: super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_sizes __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps # Fine-tuning task hyperparameters __UpperCamelCase =positive_label_weight __UpperCamelCase =num_aggregation_labels __UpperCamelCase =aggregation_loss_weight __UpperCamelCase =use_answer_as_supervision __UpperCamelCase =answer_loss_importance __UpperCamelCase =use_normalized_answer_loss __UpperCamelCase =huber_loss_delta __UpperCamelCase =temperature __UpperCamelCase =aggregation_temperature __UpperCamelCase =use_gumbel_for_cells __UpperCamelCase =use_gumbel_for_aggregation __UpperCamelCase =average_approximation_function __UpperCamelCase =cell_selection_preference __UpperCamelCase =answer_loss_cutoff __UpperCamelCase =max_num_rows __UpperCamelCase =max_num_columns __UpperCamelCase =average_logits_per_cell __UpperCamelCase =select_one_column __UpperCamelCase =allow_empty_column_selection __UpperCamelCase =init_cell_selection_weights_to_zero __UpperCamelCase =reset_position_index_per_cell __UpperCamelCase =disable_per_token_loss # Aggregation hyperparameters __UpperCamelCase =aggregation_labels __UpperCamelCase =no_aggregation_label_index if isinstance(self.aggregation_labels , _lowerCAmelCase ): __UpperCamelCase ={int(_lowerCAmelCase ): v for k, v in aggregation_labels.items()}
370
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "MCTCTFeatureExtractor" UpperCAmelCase__ : str = "AutoTokenizer" def __init__( self , A_ , A_ ) -> Dict: super().__init__(A_ , A_ ) __UpperCamelCase =self.feature_extractor __UpperCamelCase =False def __call__( self , *A_ , **A_ ) -> Optional[Any]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*A_ , **A_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) __UpperCamelCase =kwargs.pop('raw_speech' ) else: __UpperCamelCase =kwargs.pop('audio' , A_ ) __UpperCamelCase =kwargs.pop('sampling_rate' , A_ ) __UpperCamelCase =kwargs.pop('text' , A_ ) if len(A_ ) > 0: __UpperCamelCase =args[0] __UpperCamelCase =args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: __UpperCamelCase =self.feature_extractor(A_ , *A_ , sampling_rate=A_ , **A_ ) if text is not None: __UpperCamelCase =self.tokenizer(A_ , **A_ ) if text is None: return inputs elif audio is None: return encodings else: __UpperCamelCase =encodings['input_ids'] return inputs def _a ( self , *A_ , **A_ ) -> str: return self.tokenizer.batch_decode(*A_ , **A_ ) def _a ( self , *A_ , **A_ ) -> List[Any]: # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*A_ , **A_ ) __UpperCamelCase =kwargs.pop('input_features' , A_ ) __UpperCamelCase =kwargs.pop('labels' , A_ ) if len(A_ ) > 0: __UpperCamelCase =args[0] __UpperCamelCase =args[1:] if input_features is not None: __UpperCamelCase =self.feature_extractor.pad(A_ , *A_ , **A_ ) if labels is not None: __UpperCamelCase =self.tokenizer.pad(A_ , **A_ ) if labels is None: return input_features elif input_features is None: return labels else: __UpperCamelCase =labels['input_ids'] return input_features def _a ( self , *A_ , **A_ ) -> Optional[int]: return self.tokenizer.decode(*A_ , **A_ ) @contextmanager def _a ( self ) -> str: warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) __UpperCamelCase =True __UpperCamelCase =self.tokenizer yield __UpperCamelCase =self.feature_extractor __UpperCamelCase =False
117
0
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig _A = logging.get_logger(__name__) # General docstring _A = '''RegNetConfig''' # Base docstring _A = '''facebook/regnet-y-040''' _A = [1, 1_088, 7, 7] # Image classification docstring _A = '''facebook/regnet-y-040''' _A = '''tabby, tabby cat''' _A = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 3 , __UpperCamelCase = 1 , __UpperCamelCase = 1 , __UpperCamelCase = "relu" , ): """simple docstring""" super().__init__() UpperCamelCase_ = nn.Convad( __UpperCamelCase , __UpperCamelCase , kernel_size=__UpperCamelCase , stride=__UpperCamelCase , padding=kernel_size // 2 , groups=__UpperCamelCase , bias=__UpperCamelCase , ) UpperCamelCase_ = nn.BatchNormad(__UpperCamelCase ) UpperCamelCase_ = ACTaFN[activation] if activation is not None else nn.Identity() def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = self.convolution(__UpperCamelCase ) UpperCamelCase_ = self.normalization(__UpperCamelCase ) UpperCamelCase_ = self.activation(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase ): """simple docstring""" super().__init__() UpperCamelCase_ = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) UpperCamelCase_ = config.num_channels def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) UpperCamelCase_ = self.embedder(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 2 ): """simple docstring""" super().__init__() UpperCamelCase_ = nn.Convad(__UpperCamelCase , __UpperCamelCase , kernel_size=1 , stride=__UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase_ = nn.BatchNormad(__UpperCamelCase ) def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = self.convolution(__UpperCamelCase ) UpperCamelCase_ = self.normalization(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" super().__init__() UpperCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) UpperCamelCase_ = nn.Sequential( nn.Convad(__UpperCamelCase , __UpperCamelCase , kernel_size=1 ) , nn.ReLU() , nn.Convad(__UpperCamelCase , __UpperCamelCase , kernel_size=1 ) , nn.Sigmoid() , ) def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = self.pooler(__UpperCamelCase ) UpperCamelCase_ = self.attention(__UpperCamelCase ) UpperCamelCase_ = hidden_state * attention return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 1 ): """simple docstring""" super().__init__() UpperCamelCase_ = in_channels != out_channels or stride != 1 UpperCamelCase_ = max(1 , out_channels // config.groups_width ) UpperCamelCase_ = ( RegNetShortCut(__UpperCamelCase , __UpperCamelCase , stride=__UpperCamelCase ) if should_apply_shortcut else nn.Identity() ) UpperCamelCase_ = nn.Sequential( RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , stride=__UpperCamelCase , groups=__UpperCamelCase , activation=config.hidden_act ) , RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , kernel_size=1 , activation=__UpperCamelCase ) , ) UpperCamelCase_ = ACTaFN[config.hidden_act] def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = hidden_state UpperCamelCase_ = self.layer(__UpperCamelCase ) UpperCamelCase_ = self.shortcut(__UpperCamelCase ) hidden_state += residual UpperCamelCase_ = self.activation(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 1 ): """simple docstring""" super().__init__() UpperCamelCase_ = in_channels != out_channels or stride != 1 UpperCamelCase_ = max(1 , out_channels // config.groups_width ) UpperCamelCase_ = ( RegNetShortCut(__UpperCamelCase , __UpperCamelCase , stride=__UpperCamelCase ) if should_apply_shortcut else nn.Identity() ) UpperCamelCase_ = nn.Sequential( RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , stride=__UpperCamelCase , groups=__UpperCamelCase , activation=config.hidden_act ) , RegNetSELayer(__UpperCamelCase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(__UpperCamelCase , __UpperCamelCase , kernel_size=1 , activation=__UpperCamelCase ) , ) UpperCamelCase_ = ACTaFN[config.hidden_act] def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = hidden_state UpperCamelCase_ = self.layer(__UpperCamelCase ) UpperCamelCase_ = self.shortcut(__UpperCamelCase ) hidden_state += residual UpperCamelCase_ = self.activation(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 2 , __UpperCamelCase = 2 , ): """simple docstring""" super().__init__() UpperCamelCase_ = RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer UpperCamelCase_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , stride=__UpperCamelCase , ) , *[layer(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) for _ in range(depth - 1 )] , ) def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" UpperCamelCase_ = self.layers(__UpperCamelCase ) return hidden_state class lowercase_ ( nn.Module ): def __init__( self , __UpperCamelCase ): """simple docstring""" super().__init__() UpperCamelCase_ = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( __UpperCamelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) UpperCamelCase_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__UpperCamelCase , config.depths[1:] ): self.stages.append(RegNetStage(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , depth=__UpperCamelCase ) ) def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = False , __UpperCamelCase = True ): """simple docstring""" UpperCamelCase_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: UpperCamelCase_ = hidden_states + (hidden_state,) UpperCamelCase_ = stage_module(__UpperCamelCase ) if output_hidden_states: UpperCamelCase_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__UpperCamelCase , hidden_states=__UpperCamelCase ) class lowercase_ ( __lowerCamelCase ): A__ : Any = RegNetConfig A__ : Tuple = "regnet" A__ : int = "pixel_values" A__ : int = True def lowerCamelCase_ ( self , __UpperCamelCase ): """simple docstring""" if isinstance(__UpperCamelCase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(__UpperCamelCase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase=False ): """simple docstring""" if isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase_ = value _A = R'''\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n''' _A = R'''\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n''' @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""" , __lowerCamelCase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class lowercase_ ( __lowerCamelCase ): def __init__( self , __UpperCamelCase ): """simple docstring""" super().__init__(__UpperCamelCase ) UpperCamelCase_ = config UpperCamelCase_ = RegNetEmbeddings(__UpperCamelCase ) UpperCamelCase_ = RegNetEncoder(__UpperCamelCase ) UpperCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__UpperCamelCase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None ): """simple docstring""" UpperCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase_ = self.embedder(__UpperCamelCase ) UpperCamelCase_ = self.encoder( __UpperCamelCase , output_hidden_states=__UpperCamelCase , return_dict=__UpperCamelCase ) UpperCamelCase_ = encoder_outputs[0] UpperCamelCase_ = self.pooler(__UpperCamelCase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__UpperCamelCase , pooler_output=__UpperCamelCase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( """\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n """ , __lowerCamelCase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class lowercase_ ( __lowerCamelCase ): def __init__( self , __UpperCamelCase ): """simple docstring""" super().__init__(__UpperCamelCase ) UpperCamelCase_ = config.num_labels UpperCamelCase_ = RegNetModel(__UpperCamelCase ) # classification head UpperCamelCase_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__UpperCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCamelCase_ ( self , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , ): """simple docstring""" UpperCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase_ = self.regnet(__UpperCamelCase , output_hidden_states=__UpperCamelCase , return_dict=__UpperCamelCase ) UpperCamelCase_ = outputs.pooler_output if return_dict else outputs[1] UpperCamelCase_ = self.classifier(__UpperCamelCase ) UpperCamelCase_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: UpperCamelCase_ = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): UpperCamelCase_ = '''single_label_classification''' else: UpperCamelCase_ = '''multi_label_classification''' if self.config.problem_type == "regression": UpperCamelCase_ = MSELoss() if self.num_labels == 1: UpperCamelCase_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: UpperCamelCase_ = loss_fct(__UpperCamelCase , __UpperCamelCase ) elif self.config.problem_type == "single_label_classification": UpperCamelCase_ = CrossEntropyLoss() UpperCamelCase_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": UpperCamelCase_ = BCEWithLogitsLoss() UpperCamelCase_ = loss_fct(__UpperCamelCase , __UpperCamelCase ) if not return_dict: UpperCamelCase_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__UpperCamelCase , logits=__UpperCamelCase , hidden_states=outputs.hidden_states )
122
import random def lowerCAmelCase_ ( __UpperCAmelCase: list , __UpperCAmelCase: Optional[int] ) -> tuple: UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ : List[Any] = [], [], [] for element in data: if element < pivot: less.append(__UpperCAmelCase ) elif element > pivot: greater.append(__UpperCAmelCase ) else: equal.append(__UpperCAmelCase ) return less, equal, greater def lowerCAmelCase_ ( __UpperCAmelCase: list , __UpperCAmelCase: int ) -> List[str]: # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(__UpperCAmelCase ) or index < 0: return None UpperCamelCase__ : List[str] = items[random.randint(0 , len(__UpperCAmelCase ) - 1 )] UpperCamelCase__ : List[Any] = 0 UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ : int = _partition(__UpperCAmelCase , __UpperCAmelCase ) UpperCamelCase__ : Union[str, Any] = len(__UpperCAmelCase ) UpperCamelCase__ : Dict = len(__UpperCAmelCase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(__UpperCAmelCase , __UpperCAmelCase ) # must be in larger else: return quick_select(__UpperCAmelCase , index - (m + count) )
201
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a__ ( _lowercase , unittest.TestCase ): _a : List[Any] = LDMTextToImagePipeline _a : Tuple = TEXT_TO_IMAGE_PARAMS - { """negative_prompt""", """negative_prompt_embeds""", """cross_attention_kwargs""", """prompt_embeds""", } _a : Optional[Any] = PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """callback""", """callback_steps""", } _a : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS _a : Union[str, Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=3_2 , ) __lowerCAmelCase = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=__UpperCamelCase , set_alpha_to_one=__UpperCamelCase , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL( block_out_channels=(3_2, 6_4) , in_channels=3 , out_channels=3 , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , latent_channels=4 , ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) __lowerCAmelCase = CLIPTextModel(__UpperCamelCase ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __lowerCAmelCase = { "unet": unet, "scheduler": scheduler, "vqvae": vae, "bert": text_encoder, "tokenizer": tokenizer, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(__UpperCamelCase ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(__UpperCamelCase ) else: __lowerCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = LDMTextToImagePipeline(**__UpperCamelCase ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) __lowerCAmelCase = self.get_dummy_inputs(__UpperCamelCase ) __lowerCAmelCase = pipe(**__UpperCamelCase ).images __lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 1_6, 1_6, 3) __lowerCAmelCase = np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self , _A , _A=torch.floataa , _A=0 ): """simple docstring""" __lowerCAmelCase = torch.manual_seed(__UpperCamelCase ) __lowerCAmelCase = np.random.RandomState(__UpperCamelCase ).standard_normal((1, 4, 3_2, 3_2) ) __lowerCAmelCase = torch.from_numpy(__UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256" ).to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) __lowerCAmelCase = self.get_inputs(__UpperCamelCase ) __lowerCAmelCase = pipe(**__UpperCamelCase ).images __lowerCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 2_5_6, 2_5_6, 3) __lowerCAmelCase = np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78] ) __lowerCAmelCase = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self , _A , _A=torch.floataa , _A=0 ): """simple docstring""" __lowerCAmelCase = torch.manual_seed(__UpperCamelCase ) __lowerCAmelCase = np.random.RandomState(__UpperCamelCase ).standard_normal((1, 4, 3_2, 3_2) ) __lowerCAmelCase = torch.from_numpy(__UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "latents": latents, "generator": generator, "num_inference_steps": 5_0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256" ).to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) __lowerCAmelCase = self.get_inputs(__UpperCamelCase ) __lowerCAmelCase = pipe(**__UpperCamelCase ).images[0] __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy" ) __lowerCAmelCase = np.abs(expected_image - image ).max() assert max_diff < 1E-3
360
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class a__ : def __init__( self , _A , _A=1_4 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=9_9 , _A=3_2 , _A=4 , _A=4 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=0.02 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = rotary_dim __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = initializer_range __lowerCAmelCase = None __lowerCAmelCase = vocab_size - 1 __lowerCAmelCase = vocab_size - 1 __lowerCAmelCase = vocab_size - 1 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_A , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs __lowerCAmelCase = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = 2_0 __lowerCAmelCase = model_class_name(_A ) __lowerCAmelCase = model.init_cache(input_ids.shape[0] , _A ) __lowerCAmelCase = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="i4" ) __lowerCAmelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase = model( input_ids[:, :-1] , attention_mask=_A , past_key_values=_A , position_ids=_A , ) __lowerCAmelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) __lowerCAmelCase = model( input_ids[:, -1:] , attention_mask=_A , past_key_values=outputs_cache.past_key_values , position_ids=_A , ) __lowerCAmelCase = model(_A ) __lowerCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = 2_0 __lowerCAmelCase = model_class_name(_A ) __lowerCAmelCase = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) __lowerCAmelCase = model.init_cache(input_ids.shape[0] , _A ) __lowerCAmelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) __lowerCAmelCase = model( input_ids[:, :-1] , attention_mask=_A , past_key_values=_A , position_ids=_A , ) __lowerCAmelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) __lowerCAmelCase = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_A , position_ids=_A , ) __lowerCAmelCase = model(_A , attention_mask=_A ) __lowerCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) @require_flax class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : str = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () _a : Any = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = FlaxGPTJModelTester(self ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(_A , _A , _A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_class_name in self.all_model_classes: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( _A , _A , _A , _A ) @tooslow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = GPTaTokenizer.from_pretrained("gpt2" , pad_token="<|endoftext|>" , padding_side="left" ) __lowerCAmelCase = tokenizer(["Hello this is a long string", "Hey"] , return_tensors="np" , padding=_A , truncation=_A ) __lowerCAmelCase = FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ) __lowerCAmelCase = False __lowerCAmelCase = model.config.eos_token_id __lowerCAmelCase = jax.jit(model.generate ) __lowerCAmelCase = jit_generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , pad_token_id=tokenizer.pad_token_id ).sequences __lowerCAmelCase = tokenizer.batch_decode(_A , skip_special_tokens=_A ) __lowerCAmelCase = [ "Hello this is a long string of text.\n\nI'm trying to get the text of the", "Hey, I'm a little late to the party. I'm going to", ] self.assertListEqual(_A , _A ) @is_pt_flax_cross_test def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase = self._prepare_for_class(_A , _A ) __lowerCAmelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase = getattr(_A , _A ) __lowerCAmelCase , __lowerCAmelCase = pt_inputs["input_ids"].shape __lowerCAmelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_A ): __lowerCAmelCase = 0 __lowerCAmelCase = 1 __lowerCAmelCase = 0 __lowerCAmelCase = 1 __lowerCAmelCase = pt_model_class(_A ).eval() __lowerCAmelCase = model_class(_A , dtype=jnp.floataa ) __lowerCAmelCase = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _A ) __lowerCAmelCase = fx_state with torch.no_grad(): __lowerCAmelCase = pt_model(**_A ).to_tuple() __lowerCAmelCase = fx_model(**_A ).to_tuple() self.assertEqual(len(_A ) , len(_A ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(_A , _A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_A ) __lowerCAmelCase = model_class.from_pretrained(_A , from_pt=_A ) __lowerCAmelCase = fx_model_loaded(**_A ).to_tuple() self.assertEqual( len(_A ) , len(_A ) , "Output lengths differ between Flax and PyTorch" ) for fx_output_loaded, pt_output in zip(_A , _A ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs __lowerCAmelCase = self._prepare_for_class(_A , _A ) __lowerCAmelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class __lowerCAmelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning __lowerCAmelCase = getattr(_A , _A ) __lowerCAmelCase = pt_model_class(_A ).eval() __lowerCAmelCase = model_class(_A , dtype=jnp.floataa ) __lowerCAmelCase = load_flax_weights_in_pytorch_model(_A , fx_model.params ) __lowerCAmelCase , __lowerCAmelCase = pt_inputs["input_ids"].shape __lowerCAmelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_A ): __lowerCAmelCase = 0 __lowerCAmelCase = 1 __lowerCAmelCase = 0 __lowerCAmelCase = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): __lowerCAmelCase = pt_model(**_A ).to_tuple() __lowerCAmelCase = fx_model(**_A ).to_tuple() self.assertEqual(len(_A ) , len(_A ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(_A , _A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_A ) __lowerCAmelCase = pt_model_class.from_pretrained(_A , from_flax=_A ) with torch.no_grad(): __lowerCAmelCase = pt_model_loaded(**_A ).to_tuple() self.assertEqual( len(_A ) , len(_A ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(_A , _A ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_class_name in self.all_model_classes: __lowerCAmelCase = model_class_name.from_pretrained("EleutherAI/gpt-j-6B" ) __lowerCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(_A )
102
0
from __future__ import annotations from typing import Any def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" if not postfix_notation: return 0 lowercase : List[str] = {'''+''', '''-''', '''*''', '''/'''} lowercase : list[Any] = [] for token in postfix_notation: if token in operations: lowercase , lowercase : Union[str, Any] = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(_UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
337
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 __a = logging.get_logger(__name__) __a = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( A__ ): A : Any = 'yolos' def __init__( self , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=[512, 864] , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=100 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.1 , **SCREAMING_SNAKE_CASE__ , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) lowercase : Union[str, Any] = hidden_size lowercase : int = num_hidden_layers lowercase : str = num_attention_heads lowercase : str = intermediate_size lowercase : Dict = hidden_act lowercase : int = hidden_dropout_prob lowercase : Optional[Any] = attention_probs_dropout_prob lowercase : List[Any] = initializer_range lowercase : Optional[int] = layer_norm_eps lowercase : str = image_size lowercase : Dict = patch_size lowercase : str = num_channels lowercase : Optional[int] = qkv_bias lowercase : List[str] = num_detection_tokens lowercase : List[str] = use_mid_position_embeddings lowercase : Dict = auxiliary_loss # Hungarian matcher lowercase : Optional[Any] = class_cost lowercase : Any = bbox_cost lowercase : int = giou_cost # Loss coefficients lowercase : Dict = bbox_loss_coefficient lowercase : Optional[Any] = giou_loss_coefficient lowercase : Tuple = eos_coefficient class __SCREAMING_SNAKE_CASE ( A__ ): A : List[str] = version.parse('1.11' ) @property def __lowerCamelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __lowerCamelCase ( self ): return 1E-4 @property def __lowerCamelCase ( self ): return 12
337
1
"""simple docstring""" import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed UpperCAmelCase__ = 'true' def _UpperCAmelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : str=82 , __lowerCamelCase : str=16 ) -> List[str]: set_seed(42 ) _snake_case = RegressionModel() _snake_case = deepcopy(__lowerCamelCase ) _snake_case = RegressionDataset(length=__lowerCamelCase ) _snake_case = DataLoader(__lowerCamelCase , batch_size=__lowerCamelCase ) model.to(accelerator.device ) _snake_case , _snake_case = accelerator.prepare(__lowerCamelCase , __lowerCamelCase ) return model, ddp_model, dataloader def _UpperCAmelCase ( __lowerCamelCase : Accelerator , __lowerCamelCase : Optional[Any]=False ) -> Union[str, Any]: _snake_case = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) _snake_case = load_dataset('''glue''' , '''mrpc''' , split='''validation''' ) def tokenize_function(__lowerCamelCase : Union[str, Any] ): _snake_case = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__lowerCamelCase , max_length=__lowerCamelCase ) return outputs with accelerator.main_process_first(): _snake_case = dataset.map( __lowerCamelCase , batched=__lowerCamelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) _snake_case = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__lowerCamelCase : str ): if use_longest: return tokenizer.pad(__lowerCamelCase , padding='''longest''' , return_tensors='''pt''' ) return tokenizer.pad(__lowerCamelCase , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' ) return DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , collate_fn=__lowerCamelCase , batch_size=16 ) def _UpperCAmelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) -> str: _snake_case = Accelerator(dispatch_batches=__lowerCamelCase , split_batches=__lowerCamelCase ) _snake_case = get_dataloader(__lowerCamelCase , not dispatch_batches ) _snake_case = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' , return_dict=__lowerCamelCase ) _snake_case , _snake_case = accelerator.prepare(__lowerCamelCase , __lowerCamelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def _UpperCAmelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : List[str] ) -> str: _snake_case = [] for batch in dataloader: _snake_case , _snake_case = batch.values() with torch.no_grad(): _snake_case = model(__lowerCamelCase ) _snake_case , _snake_case = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) _snake_case , _snake_case = [], [] for logit, targ in logits_and_targets: logits.append(__lowerCamelCase ) targs.append(__lowerCamelCase ) _snake_case , _snake_case = torch.cat(__lowerCamelCase ), torch.cat(__lowerCamelCase ) return logits, targs def _UpperCAmelCase ( __lowerCamelCase : Accelerator , __lowerCamelCase : Dict=82 , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[str]=False , __lowerCamelCase : List[str]=16 ) -> List[Any]: _snake_case , _snake_case , _snake_case = get_basic_setup(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _snake_case , _snake_case = generate_predictions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) assert ( len(__lowerCamelCase ) == num_samples ), f'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__lowerCamelCase )}''' def _UpperCAmelCase ( __lowerCamelCase : bool = False , __lowerCamelCase : bool = False ) -> Optional[int]: _snake_case = evaluate.load('''glue''' , '''mrpc''' ) _snake_case , _snake_case = get_mrpc_setup(__lowerCamelCase , __lowerCamelCase ) # First do baseline _snake_case , _snake_case , _snake_case = setup['''no'''] model.to(__lowerCamelCase ) model.eval() for batch in dataloader: batch.to(__lowerCamelCase ) with torch.inference_mode(): _snake_case = model(**__lowerCamelCase ) _snake_case = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=__lowerCamelCase , references=batch['''labels'''] ) _snake_case = metric.compute() # Then do distributed _snake_case , _snake_case , _snake_case = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): _snake_case = model(**__lowerCamelCase ) _snake_case = outputs.logits.argmax(dim=-1 ) _snake_case = batch['''labels'''] _snake_case , _snake_case = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=__lowerCamelCase , references=__lowerCamelCase ) _snake_case = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), f'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def _UpperCAmelCase ( ) -> Union[str, Any]: _snake_case = Accelerator(split_batches=__lowerCamelCase , dispatch_batches=__lowerCamelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(__lowerCamelCase , __lowerCamelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: _snake_case = Accelerator(split_batches=__lowerCamelCase , dispatch_batches=__lowerCamelCase ) if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(__lowerCamelCase , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) _snake_case = Accelerator() test_torch_metrics(__lowerCamelCase , 5_12 ) accelerator.state._reset_state() def _UpperCAmelCase ( __lowerCamelCase : List[Any] ) -> Optional[int]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
40
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class lowerCAmelCase__ ( A_ ): __a = """roberta""" def __init__( self : str , _lowerCamelCase : Dict=50265 , _lowerCamelCase : Tuple=768 , _lowerCamelCase : List[Any]=12 , _lowerCamelCase : Any=12 , _lowerCamelCase : Optional[int]=3072 , _lowerCamelCase : Union[str, Any]="gelu" , _lowerCamelCase : Tuple=0.1 , _lowerCamelCase : Tuple=0.1 , _lowerCamelCase : Dict=512 , _lowerCamelCase : int=2 , _lowerCamelCase : str=0.0_2 , _lowerCamelCase : List[Any]=1e-12 , _lowerCamelCase : int=1 , _lowerCamelCase : int=0 , _lowerCamelCase : Union[str, Any]=2 , _lowerCamelCase : List[Any]="absolute" , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : str=None , **_lowerCamelCase : Union[str, Any] , ): super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = hidden_act _snake_case = intermediate_size _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = initializer_range _snake_case = layer_norm_eps _snake_case = position_embedding_type _snake_case = use_cache _snake_case = classifier_dropout class lowerCAmelCase__ ( A_ ): @property def lowercase ( self : Dict ): if self.task == "multiple-choice": _snake_case = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _snake_case = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
40
1
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
11
import pickle import numpy as np from matplotlib import pyplot as plt class lowerCAmelCase__ : '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=0.2 , __lowerCamelCase=0.2) -> str: _A : Optional[int] = bp_numa _A : Dict = bp_numa _A : Tuple = bp_numa _A : List[str] = conva_get[:2] _A : Tuple = conva_get[2] _A : Optional[int] = size_pa _A : Optional[Any] = rate_w _A : Optional[Any] = rate_t _A : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5) for i in range(self.conva[1]) ] _A : int = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) _A : Dict = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5) _A : Any = -2 * np.random.rand(self.conva[1]) + 1 _A : Optional[int] = -2 * np.random.rand(self.num_bpa) + 1 _A : Optional[Any] = -2 * np.random.rand(self.num_bpa) + 1 def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: # save model dict with pickle _A : Dict = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(__lowerCamelCase , "wb") as f: pickle.dump(__lowerCamelCase , __lowerCamelCase) print(F"Model saved: {save_path}") @classmethod def _lowerCamelCase ( cls , __lowerCamelCase) -> Any: # read saved model with open(__lowerCamelCase , "rb") as f: _A : Any = pickle.load(__lowerCamelCase) # noqa: S301 _A : Optional[int] = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) _A : str = model_dic.get("size_pooling1") _A : List[str] = model_dic.get("num_bp1") _A : Union[str, Any] = model_dic.get("num_bp2") _A : List[Any] = model_dic.get("num_bp3") _A : Dict = model_dic.get("rate_weight") _A : List[Any] = model_dic.get("rate_thre") # create model instance _A : str = CNN(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) # modify model parameter _A : List[Any] = model_dic.get("w_conv1") _A : Union[str, Any] = model_dic.get("wkj") _A : str = model_dic.get("vji") _A : List[str] = model_dic.get("thre_conv1") _A : Optional[Any] = model_dic.get("thre_bp2") _A : Dict = model_dic.get("thre_bp3") return conv_ins def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: return 1 / (1 + np.exp(-1 * x)) def _lowerCamelCase ( self , __lowerCamelCase) -> Union[str, Any]: return round(__lowerCamelCase , 3) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Union[str, Any]: # convolution process _A : Tuple = convs[0] _A : Union[str, Any] = convs[1] _A : List[Any] = np.shape(__lowerCamelCase)[0] # get the data slice of original image data, data_focus _A : Tuple = [] for i_focus in range(0 , size_data - size_conv + 1 , __lowerCamelCase): for j_focus in range(0 , size_data - size_conv + 1 , __lowerCamelCase): _A : Optional[int] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(__lowerCamelCase) # calculate the feature map of every single kernel, and saved as list of matrix _A : Optional[Any] = [] _A : Optional[int] = int((size_data - size_conv) / conv_step + 1) for i_map in range(__lowerCamelCase): _A : Optional[int] = [] for i_focus in range(len(__lowerCamelCase)): _A : Any = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(__lowerCamelCase)) _A : Optional[Any] = np.asmatrix(__lowerCamelCase).reshape( __lowerCamelCase , __lowerCamelCase) data_featuremap.append(__lowerCamelCase) # expanding the data slice to One dimenssion _A : Optional[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(__lowerCamelCase)) _A : Dict = np.asarray(__lowerCamelCase) return focus_list, data_featuremap def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase="average_pool") -> Dict: # pooling process _A : Optional[Any] = len(featuremaps[0]) _A : str = int(size_map / size_pooling) _A : Optional[int] = [] for i_map in range(len(__lowerCamelCase)): _A : int = featuremaps[i_map] _A : Optional[int] = [] for i_focus in range(0 , __lowerCamelCase , __lowerCamelCase): for j_focus in range(0 , __lowerCamelCase , __lowerCamelCase): _A : str = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(__lowerCamelCase)) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(__lowerCamelCase)) _A : Tuple = np.asmatrix(__lowerCamelCase).reshape(__lowerCamelCase , __lowerCamelCase) featuremap_pooled.append(__lowerCamelCase) return featuremap_pooled def _lowerCamelCase ( self , __lowerCamelCase) -> Tuple: # expanding three dimension data to one dimension list _A : Tuple = [] for i in range(len(__lowerCamelCase)): _A : Union[str, Any] = np.shape(data[i]) _A : List[Any] = data[i].reshape(1 , shapes[0] * shapes[1]) _A : Optional[Any] = data_listed.getA().tolist()[0] data_expanded.extend(__lowerCamelCase) _A : Optional[Any] = np.asarray(__lowerCamelCase) return data_expanded def _lowerCamelCase ( self , __lowerCamelCase) -> Union[str, Any]: # expanding matrix to one dimension list _A : List[Any] = np.asarray(__lowerCamelCase) _A : Union[str, Any] = np.shape(__lowerCamelCase) _A : Dict = data_mat.reshape(1 , shapes[0] * shapes[1]) return data_expanded def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase) -> Optional[int]: _A : Dict = [] _A : Any = 0 for i_map in range(__lowerCamelCase): _A : Union[str, Any] = np.ones((size_map, size_map)) for i in range(0 , __lowerCamelCase , __lowerCamelCase): for j in range(0 , __lowerCamelCase , __lowerCamelCase): _A : List[Any] = pd_pool[ i_pool ] _A : Tuple = i_pool + 1 _A : Optional[Any] = np.multiply( __lowerCamelCase , np.multiply(out_map[i_map] , (1 - out_map[i_map]))) pd_all.append(__lowerCamelCase) return pd_all def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=bool) -> Union[str, Any]: # model traning print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(__lowerCamelCase))) print((" - - Shape: Teach_Data ", np.shape(__lowerCamelCase))) _A : Tuple = 0 _A : Dict = [] _A : Optional[Any] = 1_0_0_0_0 while rp < n_repeat and mse >= error_accuracy: _A : Union[str, Any] = 0 print(F"-------------Learning Time {rp}--------------") for p in range(len(__lowerCamelCase)): # print('------------Learning Image: %d--------------'%p) _A : str = np.asmatrix(datas_train[p]) _A : Union[str, Any] = np.asarray(datas_teach[p]) _A , _A : Any = self.convolute( __lowerCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) _A : Optional[Any] = self.pooling(__lowerCamelCase , self.size_poolinga) _A : Optional[int] = np.shape(__lowerCamelCase) _A : List[str] = self._expand(__lowerCamelCase) _A : Tuple = data_bp_input _A : int = np.dot(__lowerCamelCase , self.vji.T) - self.thre_bpa _A : List[Any] = self.sig(__lowerCamelCase) _A : Union[str, Any] = np.dot(__lowerCamelCase , self.wkj.T) - self.thre_bpa _A : List[str] = self.sig(__lowerCamelCase) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- _A : int = np.multiply( (data_teach - bp_outa) , np.multiply(__lowerCamelCase , (1 - bp_outa))) _A : Optional[Any] = np.multiply( np.dot(__lowerCamelCase , self.wkj) , np.multiply(__lowerCamelCase , (1 - bp_outa))) _A : Union[str, Any] = np.dot(__lowerCamelCase , self.vji) _A : Any = pd_i_all / (self.size_poolinga * self.size_poolinga) _A : Dict = pd_conva_pooled.T.getA().tolist() _A : Optional[Any] = self._calculate_gradient_from_pool( __lowerCamelCase , __lowerCamelCase , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1]): _A : int = self._expand_mat(pd_conva_all[k_conv]) _A : Optional[int] = self.rate_weight * np.dot(__lowerCamelCase , __lowerCamelCase) _A : List[Any] = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0])) _A : Any = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv]) * self.rate_thre ) # all connected layer _A : Tuple = self.wkj + pd_k_all.T * bp_outa * self.rate_weight _A : int = self.vji + pd_j_all.T * bp_outa * self.rate_weight _A : Tuple = self.thre_bpa - pd_k_all * self.rate_thre _A : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image _A : Optional[int] = np.sum(abs(data_teach - bp_outa)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) _A : Any = rp + 1 _A : Dict = error_count / patterns all_mse.append(__lowerCamelCase) def draw_error(): _A : Optional[int] = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(__lowerCamelCase , "+-") plt.plot(__lowerCamelCase , "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(__lowerCamelCase , alpha=0.5) plt.show() print("------------------Training Complished---------------------") print((" - - Training epoch: ", rp, F" - - Mse: {mse:.6f}")) if draw_e: draw_error() return mse def _lowerCamelCase ( self , __lowerCamelCase) -> int: # model predict _A : Union[str, Any] = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(__lowerCamelCase))) for p in range(len(__lowerCamelCase)): _A : int = np.asmatrix(datas_test[p]) _A , _A : List[Any] = self.convolute( __lowerCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) _A : str = self.pooling(__lowerCamelCase , self.size_poolinga) _A : Optional[int] = self._expand(__lowerCamelCase) _A : List[Any] = data_bp_input _A : Optional[int] = bp_outa * self.vji.T - self.thre_bpa _A : int = self.sig(__lowerCamelCase) _A : int = bp_outa * self.wkj.T - self.thre_bpa _A : Optional[int] = self.sig(__lowerCamelCase) produce_out.extend(bp_outa.getA().tolist()) _A : int = [list(map(self.do_round , __lowerCamelCase)) for each in produce_out] return np.asarray(__lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: # return the data of image after convoluting process so we can check it out _A : Optional[int] = np.asmatrix(__lowerCamelCase) _A , _A : Tuple = self.convolute( __lowerCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) _A : Union[str, Any] = self.pooling(__lowerCamelCase , self.size_poolinga) return data_conveda, data_pooleda if __name__ == "__main__": pass
11
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) __A = logging.getLogger(__name__) @dataclass class lowercase_ : UpperCamelCase_ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) UpperCamelCase_ : bool = field(default=__lowercase , metadata={"help": "Whether tp freeze the encoder."} ) UpperCamelCase_ : bool = field(default=__lowercase , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowercase_ : UpperCamelCase_ : str = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCamelCase_ : Optional[str] = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) UpperCamelCase_ : Optional[int] = field( default=1_0_2_4 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_2_8 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) UpperCamelCase_ : Optional[str] = field(default=__lowercase , metadata={"help": "Source language id for translation."} ) UpperCamelCase_ : Optional[str] = field(default=__lowercase , metadata={"help": "Target language id for translation."} ) UpperCamelCase_ : Optional[int] = field(default=__lowercase , metadata={"help": "# num_beams to use for evaluation."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def snake_case_(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: """simple docstring""" logger.info(F"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(F""" {key} = {metrics[key]}""" ) save_json(_UpperCamelCase , os.path.join(_UpperCamelCase , F"""{split}_results.json""" ) ) def snake_case_() -> List[Any]: """simple docstring""" _snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _snake_case, _snake_case, _snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _snake_case, _snake_case, _snake_case = parser.parse_args_into_dataclasses() check_output_dir(_UpperCamelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , _UpperCamelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _snake_case = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _snake_case = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): assert hasattr(_UpperCamelCase , _UpperCamelCase ), F"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(_UpperCamelCase , _UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) _snake_case = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _snake_case = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=_UpperCamelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(_UpperCamelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _snake_case = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(_UpperCamelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(_UpperCamelCase , _UpperCamelCase ): _snake_case = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _snake_case = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(_UpperCamelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _snake_case = SeqaSeqDataset # Get datasets _snake_case = ( dataset_class( _UpperCamelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _snake_case = ( dataset_class( _UpperCamelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _snake_case = ( dataset_class( _UpperCamelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _snake_case = ( build_compute_metrics_fn(data_args.task , _UpperCamelCase ) if training_args.predict_with_generate else None ) _snake_case = SeqaSeqTrainer( model=_UpperCamelCase , args=_UpperCamelCase , data_args=_UpperCamelCase , train_dataset=_UpperCamelCase , eval_dataset=_UpperCamelCase , data_collator=SeqaSeqDataCollator( _UpperCamelCase , _UpperCamelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_UpperCamelCase , tokenizer=_UpperCamelCase , ) _snake_case = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _snake_case = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _snake_case = train_result.metrics _snake_case = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _snake_case = trainer.evaluate(metric_key_prefix='''val''' ) _snake_case = data_args.n_val _snake_case = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _snake_case = trainer.predict(test_dataset=_UpperCamelCase , metric_key_prefix='''test''' ) _snake_case = test_output.metrics _snake_case = data_args.n_test if trainer.is_world_process_zero(): _snake_case = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) if training_args.predict_with_generate: _snake_case = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=_UpperCamelCase , clean_up_tokenization_spaces=_UpperCamelCase ) _snake_case = lmap(str.strip , _UpperCamelCase ) write_txt_file(_UpperCamelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(_UpperCamelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def snake_case_(_UpperCamelCase ) -> List[str]: """simple docstring""" main() if __name__ == "__main__": main()
358
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) __A = logging.getLogger(__name__) @dataclass class lowercase_ : UpperCamelCase_ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) UpperCamelCase_ : bool = field(default=__lowercase , metadata={"help": "Whether tp freeze the encoder."} ) UpperCamelCase_ : bool = field(default=__lowercase , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowercase_ : UpperCamelCase_ : str = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCamelCase_ : Optional[str] = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) UpperCamelCase_ : Optional[int] = field( default=1_0_2_4 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_2_8 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) UpperCamelCase_ : Optional[int] = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) UpperCamelCase_ : Optional[int] = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) UpperCamelCase_ : Optional[str] = field(default=__lowercase , metadata={"help": "Source language id for translation."} ) UpperCamelCase_ : Optional[str] = field(default=__lowercase , metadata={"help": "Target language id for translation."} ) UpperCamelCase_ : Optional[int] = field(default=__lowercase , metadata={"help": "# num_beams to use for evaluation."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def snake_case_(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: """simple docstring""" logger.info(F"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(F""" {key} = {metrics[key]}""" ) save_json(_UpperCamelCase , os.path.join(_UpperCamelCase , F"""{split}_results.json""" ) ) def snake_case_() -> List[Any]: """simple docstring""" _snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _snake_case, _snake_case, _snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _snake_case, _snake_case, _snake_case = parser.parse_args_into_dataclasses() check_output_dir(_UpperCamelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , _UpperCamelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _snake_case = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _snake_case = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): assert hasattr(_UpperCamelCase , _UpperCamelCase ), F"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(_UpperCamelCase , _UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) _snake_case = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _snake_case = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=_UpperCamelCase , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(_UpperCamelCase , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _snake_case = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(_UpperCamelCase , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(_UpperCamelCase , _UpperCamelCase ): _snake_case = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _snake_case = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(_UpperCamelCase ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _snake_case = SeqaSeqDataset # Get datasets _snake_case = ( dataset_class( _UpperCamelCase , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _snake_case = ( dataset_class( _UpperCamelCase , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _snake_case = ( dataset_class( _UpperCamelCase , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _snake_case = ( build_compute_metrics_fn(data_args.task , _UpperCamelCase ) if training_args.predict_with_generate else None ) _snake_case = SeqaSeqTrainer( model=_UpperCamelCase , args=_UpperCamelCase , data_args=_UpperCamelCase , train_dataset=_UpperCamelCase , eval_dataset=_UpperCamelCase , data_collator=SeqaSeqDataCollator( _UpperCamelCase , _UpperCamelCase , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_UpperCamelCase , tokenizer=_UpperCamelCase , ) _snake_case = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _snake_case = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _snake_case = train_result.metrics _snake_case = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _snake_case = trainer.evaluate(metric_key_prefix='''val''' ) _snake_case = data_args.n_val _snake_case = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _snake_case = trainer.predict(test_dataset=_UpperCamelCase , metric_key_prefix='''test''' ) _snake_case = test_output.metrics _snake_case = data_args.n_test if trainer.is_world_process_zero(): _snake_case = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , _UpperCamelCase , training_args.output_dir ) all_metrics.update(_UpperCamelCase ) if training_args.predict_with_generate: _snake_case = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=_UpperCamelCase , clean_up_tokenization_spaces=_UpperCamelCase ) _snake_case = lmap(str.strip , _UpperCamelCase ) write_txt_file(_UpperCamelCase , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(_UpperCamelCase , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def snake_case_(_UpperCamelCase ) -> List[str]: """simple docstring""" main() if __name__ == "__main__": main()
278
0
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ = " " ): '''simple docstring''' snake_case_ = [] snake_case_ = 0 for index, char in enumerate(UpperCamelCase__ ): if char == separator: split_words.append(string[last_index:index] ) snake_case_ = index + 1 elif index + 1 == len(UpperCamelCase__ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
285
from __future__ import annotations import numpy as np def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ , snake_case_ = np.shape(UpperCamelCase__ ) if rows != columns: snake_case_ = ( '\'table\' has to be of square shaped array but got a ' F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(UpperCamelCase__ ) snake_case_ = np.zeros((rows, columns) ) snake_case_ = np.zeros((rows, columns) ) for i in range(UpperCamelCase__ ): for j in range(UpperCamelCase__ ): snake_case_ = sum(lower[i][k] * upper[k][j] for k in range(UpperCamelCase__ ) ) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists' ) snake_case_ = (table[i][j] - total) / upper[j][j] snake_case_ = 1 for j in range(UpperCamelCase__ , UpperCamelCase__ ): snake_case_ = sum(lower[i][k] * upper[k][j] for k in range(UpperCamelCase__ ) ) snake_case_ = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
285
1
def __UpperCAmelCase ( __a : List[str] ) -> Any: """simple docstring""" _a : int = len(__A ) while cur > 1: # Find the maximum number in arr _a : int = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _a : List[str] = arr[mi::-1] + arr[mi + 1 : len(__A )] # Reverse whole list _a : Dict = arr[cur - 1 :: -1] + arr[cur : len(__A )] cur -= 1 return arr if __name__ == "__main__": a__ = input('''Enter numbers separated by a comma:\n''').strip() a__ = [int(item) for item in user_input.split(''',''')] print(pancake_sort(unsorted))
357
import argparse import os import re import packaging.version a__ = '''examples/''' a__ = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } a__ = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } a__ = '''README.md''' def __UpperCAmelCase ( __a : List[str] ,__a : int ,__a : Optional[Any] ) -> int: """simple docstring""" with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Tuple = f.read() _a , _a : str = REPLACE_PATTERNS[pattern] _a : List[str] = replace.replace('''VERSION''' ,__a ) _a : List[Any] = re_pattern.sub(__a ,__a ) with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.write(__a ) def __UpperCAmelCase ( __a : Any ) -> List[Any]: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a ,__a ) ,__a ,pattern='''examples''' ) def __UpperCAmelCase ( __a : List[Any] ,__a : List[str]=False ) -> int: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a ,__a ,__a ) if not patch: update_version_in_examples(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" _a : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' _a : str = '''1. Want to contribute a new model?''' with open(__a ,'''r''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: _a : Optional[int] = f.readlines() # Find the start of the list. _a : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _a : List[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): _a : Tuple = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' ,'''https://huggingface.co/docs/transformers/model_doc''' ,) index += 1 with open(__a ,'''w''' ,encoding='''utf-8''' ,newline='''\n''' ) as f: f.writelines(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] ,'''r''' ) as f: _a : Optional[Any] = f.read() _a : Optional[Any] = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def __UpperCAmelCase ( __a : Dict=False ) -> str: """simple docstring""" _a : Optional[Any] = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: _a : List[Any] = default_version.base_version elif patch: _a : str = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _a : List[str] = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _a : Dict = input(F"""Which version are you releasing? [{default_version}]""" ) if len(__a ) == 0: _a : int = default_version print(F"""Updating version to {version}.""" ) global_version_update(__a ,patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def __UpperCAmelCase ( ) -> Tuple: """simple docstring""" _a : str = get_version() _a : int = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _a : List[Any] = current_version.base_version # Check with the user we got that right. _a : Union[str, Any] = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(__a ) == 0: _a : List[str] = dev_version print(F"""Updating version to {version}.""" ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') a__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
15
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss SCREAMING_SNAKE_CASE :Dict = pytest.mark.integration @require_faiss class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): __A = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A ) for x in np.arange(30 ).tolist()]} ) return dset def UpperCamelCase_ ( self : Optional[Any] ): import faiss __A = self._create_dummy_dataset() __A = dset.map( lambda A ,A : {"vecs": i * np.ones(5 ,dtype=np.floataa )} ,with_indices=A ,keep_in_memory=A ) __A = dset.add_faiss_index("vecs" ,batch_size=1_00 ,metric_type=faiss.METRIC_INNER_PRODUCT ) __A , __A = dset.get_nearest_examples("vecs" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) dset.drop_index("vecs" ) def UpperCamelCase_ ( self : Tuple ): import faiss __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ,batch_size=1_00 ,metric_type=faiss.METRIC_INNER_PRODUCT ,) __A , __A = dset.get_nearest_examples("vecs" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) def UpperCamelCase_ ( self : List[str] ): import faiss __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ,metric_type=faiss.METRIC_INNER_PRODUCT ,) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A ) as tmp_file: dset.save_faiss_index("vecs" ,tmp_file.name ) dset.load_faiss_index("vecs2" ,tmp_file.name ) os.unlink(tmp_file.name ) __A , __A = dset.get_nearest_examples("vecs2" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A ,partial(dset.get_nearest_examples ,"vecs2" ,np.ones(5 ,dtype=np.floataa ) ) ) def UpperCamelCase_ ( self : Dict ): from elasticsearch import Elasticsearch __A = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __A = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) __A = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} __A = Elasticsearch() dset.add_elasticsearch_index("filename" ,es_client=A ) __A , __A = dset.get_nearest_examples("filename" ,"my_name-train_29" ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) @require_faiss class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[int] ): import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal ,5 ) index.add_vectors(np.zeros((5, 5) ,dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal ,10 ) # single query __A = np.zeros(5 ,dtype=np.floataa ) __A = 1 __A , __A = index.search(A ) self.assertRaises(A ,index.search ,query.reshape(-1 ,1 ) ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) # batched queries __A = np.eye(5 ,dtype=np.floataa )[::-1] __A , __A = index.search_batch(A ) self.assertRaises(A ,index.search_batch ,queries[0] ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([4, 3, 2, 1, 0] ,A ) def UpperCamelCase_ ( self : Tuple ): import faiss __A = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) __A = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexLSH ) with self.assertRaises(A ): __A = FaissIndex(string_factory="Flat" ,custom_index=faiss.IndexFlat(5 ) ) def UpperCamelCase_ ( self : Any ): import faiss __A = faiss.IndexFlat(5 ) __A = FaissIndex(custom_index=A ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) def UpperCamelCase_ ( self : Union[str, Any] ): import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A ) as tmp_file: index.save(tmp_file.name ) __A = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __A = np.zeros(5 ,dtype=np.floataa ) __A = 1 __A , __A = index.search(A ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) @require_faiss def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) __A = "index.faiss" __A = F'''mock://{index_name}''' index.save(a_ , storage_options=mockfs.storage_options ) __A = FaissIndex.load(a_ , storage_options=mockfs.storage_options ) __A = np.zeros(5 , dtype=np.floataa ) __A = 1 __A , __A = index.search(a_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Dict ): from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __A = Elasticsearch() __A = {"acknowledged": True} __A = ElasticSearchIndex(es_client=A ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query __A = "foo" __A = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __A , __A = index.search(A ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # single query with timeout __A = "foo" __A = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __A , __A = index.search(A ,request_timeout=30 ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # batched queries __A = ["foo", "bar", "foobar"] __A = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __A , __A = index.search_batch(A ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([1, 1, 1] ,A ) # batched queries with timeout __A = ["foo", "bar", "foobar"] __A = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __A , __A = index.search_batch(A ,request_timeout=30 ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([1, 1, 1] ,A )
15
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _UpperCAmelCase = {"""configuration_encoder_decoder""": ["""EncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""EncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""TFEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["""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 _UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
140
0
'''simple docstring''' import string from math import logaa def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: __lowerCamelCase = document.translate( str.maketrans('''''' , '''''' , string.punctuation ) ).replace('''\n''' , '''''' ) __lowerCamelCase = document_without_punctuation.split(''' ''' ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> tuple[int, int]: __lowerCamelCase = corpus.lower().translate( str.maketrans('''''' , '''''' , string.punctuation ) ) # strip all punctuation and replace it with '' __lowerCamelCase = corpus_without_punctuation.split('''\n''' ) __lowerCamelCase = term.lower() return (len([doc for doc in docs if term in doc] ), len(UpperCamelCase__ )) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=False ) -> float: if smoothing: if n == 0: raise ValueError('''log10(0) is undefined.''' ) return round(1 + logaa(n / (1 + df) ) , 3 ) if df == 0: raise ZeroDivisionError('''df must be > 0''' ) elif n == 0: raise ValueError('''log10(0) is undefined.''' ) return round(logaa(n / df ) , 3 ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: return round(tf * idf , 3 )
364
'''simple docstring''' from __future__ import annotations def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> list[list[int]]: __lowerCamelCase = [] create_all_state(1 , UpperCamelCase__ , UpperCamelCase__ , [] , UpperCamelCase__ ) return result def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) -> None: if level == 0: total_list.append(current_list[:] ) return for i in range(UpperCamelCase__ , total_number - level + 2 ): current_list.append(UpperCamelCase__ ) create_all_state(i + 1 , UpperCamelCase__ , level - 1 , UpperCamelCase__ , UpperCamelCase__ ) current_list.pop() def __lowerCAmelCase ( UpperCamelCase__ ) -> None: for i in total_list: print(*UpperCamelCase__ ) if __name__ == "__main__": __UpperCAmelCase =4 __UpperCAmelCase =2 __UpperCAmelCase =generate_all_combinations(n, k) print_all_state(total_list)
237
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowercase__ :List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Union[str, Any] = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys lowercase__ :List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
101
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowercase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): lowercase_ : Tuple =ShapEPipeline lowercase_ : List[Any] =['''prompt'''] lowercase_ : int =['''prompt'''] lowercase_ : Union[str, Any] =[ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] lowercase_ : Optional[int] =False @property def A__ ( self): return 3_2 @property def A__ ( self): return 3_2 @property def A__ ( self): return self.time_input_dim * 4 @property def A__ ( self): return 8 @property def A__ ( self): lowercase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') return tokenizer @property def A__ ( self): torch.manual_seed(0) lowercase = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=self.text_embedder_hidden_size ,projection_dim=self.text_embedder_hidden_size ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,) return CLIPTextModelWithProjection(A__) @property def A__ ( self): torch.manual_seed(0) lowercase = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_6, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 3_2, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase = PriorTransformer(**A__) return model @property def A__ ( self): torch.manual_seed(0) lowercase = { '''param_shapes''': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 1_2, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase = ShapERenderer(**A__) return model def A__ ( self): lowercase = self.dummy_prior lowercase = self.dummy_text_encoder lowercase = self.dummy_tokenizer lowercase = self.dummy_renderer lowercase = HeunDiscreteScheduler( beta_schedule='''exp''' ,num_train_timesteps=1_0_2_4 ,prediction_type='''sample''' ,use_karras_sigmas=A__ ,clip_sample=A__ ,clip_sample_range=1.0 ,) lowercase = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def A__ ( self ,A__ ,A__=0): if str(A__).startswith('''mps'''): lowercase = torch.manual_seed(A__) else: lowercase = torch.Generator(device=A__).manual_seed(A__) lowercase = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 3_2, '''output_type''': '''np''', } return inputs def A__ ( self): lowercase = '''cpu''' lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = pipe(**self.get_dummy_inputs(A__)) lowercase = output.images[0] lowercase = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) lowercase = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def A__ ( self): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2]) def A__ ( self): lowercase = torch_device == '''cpu''' lowercase = True self._test_inference_batch_single_identical( batch_size=2 ,test_max_difference=A__ ,relax_max_difference=A__ ,) def A__ ( self): lowercase = self.get_dummy_components() lowercase = self.pipeline_class(**A__) lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = 1 lowercase = 2 lowercase = self.get_dummy_inputs(A__) for key in inputs.keys(): if key in self.batch_params: lowercase = batch_size * [inputs[key]] lowercase = pipe(**A__ ,num_images_per_prompt=A__)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def A__ ( self): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self): lowercase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''') lowercase = ShapEPipeline.from_pretrained('''openai/shap-e''') lowercase = pipe.to(A__) pipe.set_progress_bar_config(disable=A__) lowercase = torch.Generator(device=A__).manual_seed(0) lowercase = pipe( '''a shark''' ,generator=A__ ,guidance_scale=15.0 ,num_inference_steps=6_4 ,frame_size=6_4 ,output_type='''np''' ,).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(A__ ,A__)
101
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( UpperCamelCase_ ): UpperCamelCase_ = filter(lambda UpperCamelCase_ : p.requires_grad , model.parameters() ) UpperCamelCase_ = sum([np.prod(p.size() ) for p in model_parameters] ) return params _UpperCAmelCase = logging.getLogger(__name__) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ): if metric == "rouge2": UpperCamelCase_ = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": UpperCamelCase_ = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": UpperCamelCase_ = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' " function." ) UpperCamelCase_ = ModelCheckpoint( dirpath=_lowerCamelCase , filename=_lowerCamelCase , monitor=F'''val_{metric}''' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ): return EarlyStopping( monitor=F'''val_{metric}''' , mode="min" if "loss" in metric else "max" , patience=_lowerCamelCase , verbose=_lowerCamelCase , ) class _UpperCamelCase ( pl.Callback ): def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Dict ) -> Tuple: """simple docstring""" UpperCamelCase_ = {f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_SCREAMING_SNAKE_CASE ) @rank_zero_only def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: pl.LightningModule , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: str=True ) -> List[Any]: """simple docstring""" logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) UpperCamelCase_ = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results UpperCamelCase_ = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCamelCase_ = od / "test_results.txt" UpperCamelCase_ = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. UpperCamelCase_ = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' UpperCamelCase_ = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) generations_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , "a+" ) as writer: for key in sorted(_SCREAMING_SNAKE_CASE ): if key in ["log", "progress_bar", "preds"]: continue UpperCamelCase_ = metrics[key] if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): UpperCamelCase_ = val.item() UpperCamelCase_ = f'''{key}: {val:.6f}\n''' writer.write(_SCREAMING_SNAKE_CASE ) if not save_generations: return if "preds" in metrics: UpperCamelCase_ = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_SCREAMING_SNAKE_CASE ) @rank_zero_only def lowercase ( self: int , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: int ) -> Optional[int]: """simple docstring""" try: UpperCamelCase_ = pl_module.model.model.num_parameters() except AttributeError: UpperCamelCase_ = pl_module.model.num_parameters() UpperCamelCase_ = count_trainable_parameters(_SCREAMING_SNAKE_CASE ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: pl.LightningModule ) -> Dict: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , "test" ) @rank_zero_only def lowercase ( self: int , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: Optional[int] ) -> Optional[int]: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
370
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = DiTPipeline _UpperCamelCase : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _UpperCamelCase : Dict = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } _UpperCamelCase : Optional[int] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _UpperCamelCase : Dict = False def lowercase ( self: str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn="gelu-approximate" , num_embeds_ada_norm=1000 , norm_type="ada_norm_zero" , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = AutoencoderKL() UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=0 ) -> Dict: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowercase ( self: Any ) -> List[str]: """simple docstring""" UpperCamelCase_ = "cpu" UpperCamelCase_ = self.get_dummy_components() UpperCamelCase_ = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(**_SCREAMING_SNAKE_CASE ).images UpperCamelCase_ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) UpperCamelCase_ = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) UpperCamelCase_ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella", "white shark", "white wolf"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) UpperCamelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
328
0
"""simple docstring""" from importlib import import_module from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class __snake_case : def __init__( self : int , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any]=None ): """simple docstring""" _lowerCamelCase : Tuple = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) _lowerCamelCase : Any = module._original_module if isinstance(__lowerCAmelCase , _PatchedModuleObj ) else module class __snake_case : snake_case__ : Dict = [] def __init__( self : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=None ): """simple docstring""" _lowerCamelCase : Optional[Any] = obj _lowerCamelCase : int = target _lowerCamelCase : int = new _lowerCamelCase : Tuple = target.split('''.''' )[0] _lowerCamelCase : Optional[Any] = {} _lowerCamelCase : Optional[int] = attrs or [] def __enter__( self : Optional[Any] ): """simple docstring""" *_lowerCamelCase , _lowerCamelCase : Optional[int] = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__lowerCAmelCase ) ): try: _lowerCamelCase : Union[str, Any] = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): _lowerCamelCase : Dict = getattr(self.obj , __lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): _lowerCamelCase : Dict = obj_attr # patch at top level setattr(self.obj , __lowerCAmelCase , _PatchedModuleObj(__lowerCAmelCase , attrs=self.attrs ) ) _lowerCamelCase : Tuple = getattr(self.obj , __lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__lowerCAmelCase , __lowerCAmelCase , _PatchedModuleObj(getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) , attrs=self.attrs ) ) _lowerCamelCase : int = getattr(__lowerCAmelCase , __lowerCAmelCase ) # finally set the target attribute setattr(__lowerCAmelCase , __lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: _lowerCamelCase : Optional[int] = getattr(import_module('''.'''.join(__lowerCAmelCase ) ) , __lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __lowerCAmelCase ) is attr_value: _lowerCamelCase : str = getattr(self.obj , __lowerCAmelCase ) setattr(self.obj , __lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" _lowerCamelCase : List[str] = globals()['''__builtins__'''][target_attr] setattr(self.obj , __lowerCAmelCase , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : Any , *__lowerCAmelCase : Dict ): """simple docstring""" for attr in list(self.original ): setattr(self.obj , __lowerCAmelCase , self.original.pop(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.__enter__() self._active_patches.append(self ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
72
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __snake_case ( _lowercase): snake_case__ : List[Any] = "Speech2TextFeatureExtractor" snake_case__ : Union[str, Any] = "Speech2TextTokenizer" def __init__( self : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" super().__init__(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[str] = self.feature_extractor _lowerCamelCase : str = False def __call__( self : List[Any] , *__lowerCAmelCase : int , **__lowerCAmelCase : List[str] ): """simple docstring""" if self._in_target_context_manager: return self.current_processor(*__lowerCAmelCase , **__lowerCAmelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) _lowerCamelCase : str = kwargs.pop('''raw_speech''' ) else: _lowerCamelCase : Tuple = kwargs.pop('''audio''' , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = kwargs.pop('''sampling_rate''' , __lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = kwargs.pop('''text''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : List[Any] = args[0] _lowerCamelCase : int = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: _lowerCamelCase : List[Any] = self.feature_extractor(__lowerCAmelCase , *__lowerCAmelCase , sampling_rate=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None: _lowerCamelCase : List[Any] = self.tokenizer(__lowerCAmelCase , **__lowerCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: _lowerCamelCase : List[str] = encodings['''input_ids'''] return inputs def SCREAMING_SNAKE_CASE ( self : Any , *__lowerCAmelCase : List[Any] , **__lowerCAmelCase : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : int ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @contextmanager def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : Any = self.tokenizer yield _lowerCamelCase : List[str] = self.feature_extractor _lowerCamelCase : Tuple = False
72
1
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __UpperCamelCase ( lowerCAmelCase__ : Tuple ): __a : int = int(number**0.5 ) return number == sq * sq def __UpperCamelCase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(__lowerCamelCase , __lowerCamelCase ) top //= hcf bottom //= hcf return top, bottom def __UpperCamelCase ( lowerCAmelCase__ : List[str] = 3_5 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : List[str] = x_den * y_den __a : Tuple = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Union[str, Any] = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 __a : Union[str, Any] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : int = x_den * x_den * y_den * y_den if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): __a : List[Any] = int(sqrt(__lowerCamelCase ) ) __a : List[str] = int(sqrt(__lowerCamelCase ) ) __a : Tuple = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Tuple = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=-1 __a : Any = x_num * y_num __a : Dict = x_den * y_num + x_num * y_den __a : Any = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) # n=2 __a : Optional[Any] = x_num * x_num * y_num * y_num __a : Union[str, Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCamelCase ) and is_sq(__lowerCamelCase ): __a : Tuple = int(sqrt(__lowerCamelCase ) ) __a : List[Any] = int(sqrt(__lowerCamelCase ) ) __a : List[Any] = gcd(__lowerCamelCase , __lowerCamelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) unique_s.add(__lowerCamelCase ) for num, den in unique_s: total += Fraction(__lowerCamelCase , __lowerCamelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
351
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): @slow def lowerCAmelCase (self : Tuple ): __a : List[str] = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=snake_case_ ).to(snake_case_ ) __a : List[Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __a : Optional[int] = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids __a : Dict = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids __a : Optional[Any] = model(input_ids.to(snake_case_ ) , labels=labels.to(snake_case_ ) ).loss __a : Tuple = -(labels.shape[-1] * loss.item()) __a : Dict = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
90
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
35
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ : Optional[Any] = {'configuration_ibert': ['IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'IBertConfig', 'IBertOnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[str] = [ 'IBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'IBertForMaskedLM', 'IBertForMultipleChoice', 'IBertForQuestionAnswering', 'IBertForSequenceClassification', 'IBertForTokenClassification', 'IBertModel', 'IBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys snake_case__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
117
0
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' pass class lowerCAmelCase_: '''simple docstring''' def __init__( self ,__UpperCAmelCase ) -> None: lowerCAmelCase__ : Any = data lowerCAmelCase__ : Node | None = None def __iter__( self ) -> int: lowerCAmelCase__ : Any = self lowerCAmelCase__ : Union[str, Any] = [] while node: if node in visited: raise ContainsLoopError visited.append(__UpperCAmelCase ) yield node.data lowerCAmelCase__ : str = node.next_node @property def UpperCAmelCase_ ( self ) -> bool: try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCAmelCase = Node(1) _lowerCAmelCase = Node(2) _lowerCAmelCase = Node(3) _lowerCAmelCase = Node(4) print(root_node.has_loop) # False _lowerCAmelCase = root_node.next_node print(root_node.has_loop) # True _lowerCAmelCase = Node(5) _lowerCAmelCase = Node(6) _lowerCAmelCase = Node(5) _lowerCAmelCase = Node(6) print(root_node.has_loop) # False _lowerCAmelCase = Node(1) print(root_node.has_loop) # False
359
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowercase : List[str] = IFInpaintingSuperResolutionPipeline __lowercase : int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) __lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase_ ( self ) -> Any: return self._get_superresolution_dummy_components() def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase=0 ) -> List[Any]: if str(__UpperCAmelCase ).startswith("""mps""" ): lowerCAmelCase__ : Any = torch.manual_seed(__UpperCAmelCase ) else: lowerCAmelCase__ : Dict = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCAmelCase__ : Tuple = floats_tensor((1, 3, 16, 16) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Any = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) lowerCAmelCase__ : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def UpperCAmelCase_ ( self ) -> Union[str, Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def UpperCAmelCase_ ( self ) -> Optional[int]: self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" ,reason="""float16 requires CUDA""" ) def UpperCAmelCase_ ( self ) -> List[Any]: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCAmelCase_ ( self ) -> str: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCAmelCase_ ( self ) -> List[Any]: self._test_save_load_local() def UpperCAmelCase_ ( self ) -> int: self._test_inference_batch_single_identical( expected_max_diff=1E-2 ,)
184
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def snake_case ( A__ ): return ConvertCommand( args.model_type ,args.tf_checkpoint ,args.pytorch_dump_output ,args.config ,args.finetuning_task_name ) lowerCamelCase_ = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class UpperCamelCase_ (__A ): @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : ArgumentParser ) -> List[Any]: UpperCAmelCase_ : Dict = parser.add_parser( "convert" , help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints." , ) train_parser.add_argument("--model_type" , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Model's type." ) train_parser.add_argument( "--tf_checkpoint" , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="TensorFlow checkpoint path or folder." ) train_parser.add_argument( "--pytorch_dump_output" , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to the PyTorch saved model output." ) train_parser.add_argument("--config" , type=lowerCAmelCase_ , default="" , help="Configuration file path or folder." ) train_parser.add_argument( "--finetuning_task_name" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Optional fine-tuning task name if the TF model was a finetuned model." , ) train_parser.set_defaults(func=lowerCAmelCase_ ) def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str , *lowerCAmelCase_ : Optional[int] , ) -> Tuple: UpperCAmelCase_ : List[Any] = logging.get_logger("transformers-cli/converting" ) self._logger.info(f"""Loading model {model_type}""" ) UpperCAmelCase_ : Any = model_type UpperCAmelCase_ : Dict = tf_checkpoint UpperCAmelCase_ : Dict = pytorch_dump_output UpperCAmelCase_ : str = config UpperCAmelCase_ : Optional[int] = finetuning_task_name def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(lowerCAmelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) if "ckpt" in self._tf_checkpoint.lower(): UpperCAmelCase_ : Dict = self._tf_checkpoint UpperCAmelCase_ : Optional[int] = "" else: UpperCAmelCase_ : str = self._tf_checkpoint UpperCAmelCase_ : str = "" convert_transfo_xl_checkpoint_to_pytorch( lowerCAmelCase_ , self._config , self._pytorch_dump_output , lowerCAmelCase_ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase_ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]" )
268
"""simple docstring""" import os def snake_case ( ): with open(os.path.dirname(A__ ) + "/grid.txt" ) as f: UpperCAmelCase_ : Any = [] # noqa: E741 for _ in range(20 ): l.append([int(A__ ) for x in f.readline().split()] ) UpperCAmelCase_ : Any = 0 # right for i in range(20 ): for j in range(17 ): UpperCAmelCase_ : Union[str, Any] = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: UpperCAmelCase_ : Any = temp # down for i in range(17 ): for j in range(20 ): UpperCAmelCase_ : List[Any] = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: UpperCAmelCase_ : Tuple = temp # diagonal 1 for i in range(17 ): for j in range(17 ): UpperCAmelCase_ : str = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: UpperCAmelCase_ : List[str] = temp # diagonal 2 for i in range(17 ): for j in range(3 ,20 ): UpperCAmelCase_ : List[Any] = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: UpperCAmelCase_ : List[str] = temp return maximum if __name__ == "__main__": print(solution())
268
1
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging __snake_case : Tuple = logging.get_logger(__name__) __snake_case : int = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = 'codegen' SCREAMING_SNAKE_CASE = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self: Any , _SCREAMING_SNAKE_CASE: Dict=5_0400 , _SCREAMING_SNAKE_CASE: Optional[Any]=2048 , _SCREAMING_SNAKE_CASE: List[str]=2048 , _SCREAMING_SNAKE_CASE: Optional[int]=4096 , _SCREAMING_SNAKE_CASE: List[Any]=28 , _SCREAMING_SNAKE_CASE: Dict=16 , _SCREAMING_SNAKE_CASE: Dict=64 , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: Optional[Any]="gelu_new" , _SCREAMING_SNAKE_CASE: str=0.0 , _SCREAMING_SNAKE_CASE: int=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.0 , _SCREAMING_SNAKE_CASE: Union[str, Any]=1e-5 , _SCREAMING_SNAKE_CASE: Any=0.02 , _SCREAMING_SNAKE_CASE: List[str]=True , _SCREAMING_SNAKE_CASE: int=5_0256 , _SCREAMING_SNAKE_CASE: Optional[int]=5_0256 , _SCREAMING_SNAKE_CASE: Dict=False , **_SCREAMING_SNAKE_CASE: Union[str, Any] , ) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = vocab_size __lowerCAmelCase : Any = n_ctx __lowerCAmelCase : Tuple = n_positions __lowerCAmelCase : Dict = n_embd __lowerCAmelCase : Optional[Any] = n_layer __lowerCAmelCase : Tuple = n_head __lowerCAmelCase : List[str] = n_inner __lowerCAmelCase : Union[str, Any] = rotary_dim __lowerCAmelCase : Optional[Any] = activation_function __lowerCAmelCase : str = resid_pdrop __lowerCAmelCase : List[Any] = embd_pdrop __lowerCAmelCase : Any = attn_pdrop __lowerCAmelCase : Optional[int] = layer_norm_epsilon __lowerCAmelCase : List[str] = initializer_range __lowerCAmelCase : List[Any] = use_cache __lowerCAmelCase : List[Any] = bos_token_id __lowerCAmelCase : Optional[int] = eos_token_id super().__init__( bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , tie_word_embeddings=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: List[str] , _SCREAMING_SNAKE_CASE: PretrainedConfig , _SCREAMING_SNAKE_CASE: str = "default" , _SCREAMING_SNAKE_CASE: List[PatchingSpec] = None , _SCREAMING_SNAKE_CASE: bool = False , ) -> Tuple: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , task=_SCREAMING_SNAKE_CASE , patching_specs=_SCREAMING_SNAKE_CASE , use_past=_SCREAMING_SNAKE_CASE) if not getattr(self._config , "pad_token_id" , _SCREAMING_SNAKE_CASE): # TODO: how to do that better? __lowerCAmelCase : List[str] = 0 @property def _SCREAMING_SNAKE_CASE ( self: int) -> Mapping[str, Mapping[int, str]]: """simple docstring""" __lowerCAmelCase : Optional[Any] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}) if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="inputs") __lowerCAmelCase : Dict = {0: "batch", 1: "past_sequence + sequence"} else: __lowerCAmelCase : Tuple = {0: "batch", 1: "sequence"} return common_inputs @property def _SCREAMING_SNAKE_CASE ( self: Dict) -> int: """simple docstring""" return self._config.n_layer @property def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> int: """simple docstring""" return self._config.n_head def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: PreTrainedTokenizer , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" __lowerCAmelCase : List[Any] = super(_SCREAMING_SNAKE_CASE , self).generate_dummy_inputs( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE) # We need to order the input in the way they appears in the forward() __lowerCAmelCase : Optional[Any] = OrderedDict({"input_ids": common_inputs["input_ids"]}) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.") else: import torch __lowerCAmelCase : int = common_inputs["input_ids"].shape # Not using the same length for past_key_values __lowerCAmelCase : Optional[int] = seqlen + 2 __lowerCAmelCase : int = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __lowerCAmelCase : Optional[int] = [ (torch.zeros(_SCREAMING_SNAKE_CASE), torch.zeros(_SCREAMING_SNAKE_CASE)) for _ in range(self.num_layers) ] __lowerCAmelCase : Any = common_inputs["attention_mask"] if self.use_past: __lowerCAmelCase : Union[str, Any] = ordered_inputs["attention_mask"].dtype __lowerCAmelCase : Tuple = torch.cat( [ordered_inputs["attention_mask"], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE)] , dim=1) return ordered_inputs @property def _SCREAMING_SNAKE_CASE ( self: Tuple) -> int: """simple docstring""" return 13
352
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def _lowercase ( __snake_case ) -> Dict: return {key.lstrip("-" ): value for key, value in zip(unknown_args[::2] ,unknown_args[1::2] )} def _lowercase ( ) -> Union[str, Any]: __lowerCAmelCase : List[str] = ArgumentParser( "HuggingFace Datasets CLI tool" ,usage="datasets-cli <command> [<args>]" ,allow_abbrev=__snake_case ) __lowerCAmelCase : str = parser.add_subparsers(help="datasets-cli command helpers" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__snake_case ) EnvironmentCommand.register_subcommand(__snake_case ) TestCommand.register_subcommand(__snake_case ) RunBeamCommand.register_subcommand(__snake_case ) DummyDataCommand.register_subcommand(__snake_case ) # Parse args __lowerCAmelCase , __lowerCAmelCase : Any = parser.parse_known_args() if not hasattr(__snake_case ,"func" ): parser.print_help() exit(1 ) __lowerCAmelCase : List[Any] = parse_unknown_args(__snake_case ) # Run __lowerCAmelCase : Union[str, Any] = args.func(__snake_case ,**__snake_case ) service.run() if __name__ == "__main__": main()
58
0