code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a : Dict = """platform""" import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __UpperCAmelCase: """simple docstring""" __lowerCamelCase = PegasusConfig __lowerCamelCase = {} __lowerCamelCase = "gelu" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=False , snake_case__=99 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=20 , snake_case__=2 , snake_case__=1 , snake_case__=0 , ): '''simple docstring''' lowercase__ : Tuple= parent lowercase__ : int= batch_size lowercase__ : Tuple= seq_length lowercase__ : int= is_training lowercase__ : Optional[int]= use_labels lowercase__ : int= vocab_size lowercase__ : Optional[Any]= hidden_size lowercase__ : int= num_hidden_layers lowercase__ : List[Any]= num_attention_heads lowercase__ : Optional[Any]= intermediate_size lowercase__ : int= hidden_dropout_prob lowercase__ : List[str]= attention_probs_dropout_prob lowercase__ : List[str]= max_position_embeddings lowercase__ : List[Any]= eos_token_id lowercase__ : Tuple= pad_token_id lowercase__ : Any= bos_token_id def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) lowercase__ : Dict= np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) lowercase__ : Optional[Any]= np.concatenate([input_ids, eos_tensor] , axis=1 ) lowercase__ : Optional[int]= ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : Union[str, Any]= 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 , ) lowercase__ : List[str]= prepare_pegasus_inputs_dict(snake_case__ , snake_case__ , snake_case__ ) return config, inputs_dict def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : int= 20 lowercase__ : Optional[int]= model_class_name(snake_case__ ) lowercase__ : Optional[Any]= model.encode(inputs_dict["input_ids"] ) lowercase__ : Optional[int]= ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowercase__ : List[str]= model.init_cache(decoder_input_ids.shape[0] , snake_case__ , snake_case__ ) lowercase__ : Dict= jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) lowercase__ : Any= jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ : List[str]= model.decode( decoder_input_ids[:, :-1] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=snake_case__ , decoder_position_ids=snake_case__ , ) lowercase__ : Optional[int]= jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowercase__ : Optional[int]= model.decode( decoder_input_ids[:, -1:] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=snake_case__ , ) lowercase__ : Dict= model.decode(snake_case__ , snake_case__ ) lowercase__ : Optional[int]= 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 UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : List[str]= 20 lowercase__ : List[str]= model_class_name(snake_case__ ) lowercase__ : Union[str, Any]= model.encode(inputs_dict["input_ids"] ) lowercase__ : Tuple= ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowercase__ : Optional[Any]= jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowercase__ : Any= model.init_cache(decoder_input_ids.shape[0] , snake_case__ , snake_case__ ) lowercase__ : Tuple= jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ : List[Any]= model.decode( decoder_input_ids[:, :-1] , snake_case__ , decoder_attention_mask=snake_case__ , past_key_values=snake_case__ , decoder_position_ids=snake_case__ , ) lowercase__ : List[Any]= jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowercase__ : int= model.decode( decoder_input_ids[:, -1:] , snake_case__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=snake_case__ , decoder_position_ids=snake_case__ , ) lowercase__ : List[str]= model.decode(snake_case__ , snake_case__ , decoder_attention_mask=snake_case__ ) lowercase__ : Any= 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 lowercase__(A , A , A , A=None , A=None , ) ->Union[str, Any]: """simple docstring""" if attention_mask is None: lowercase__ : Optional[int]= np.not_equal(A , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: lowercase__ : List[str]= np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __lowerCamelCase = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= FlaxPegasusModelTester(self ) lowercase__ : Tuple= ConfigTester(self , config_class=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ : List[Any]= self._prepare_for_class(snake_case__ , snake_case__ ) lowercase__ : Optional[int]= model_class(snake_case__ ) @jax.jit def encode_jitted(snake_case__ , snake_case__=None , **snake_case__ ): return model.encode(input_ids=snake_case__ , attention_mask=snake_case__ ) with self.subTest("JIT Enabled" ): lowercase__ : Any= encode_jitted(**snake_case__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowercase__ : Dict= encode_jitted(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) ) for jitted_output, output in zip(snake_case__ , snake_case__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ : Optional[int]= model_class(snake_case__ ) lowercase__ : Optional[Any]= model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) lowercase__ : Tuple= { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(snake_case__ , snake_case__ , snake_case__ ): return model.decode( decoder_input_ids=snake_case__ , decoder_attention_mask=snake_case__ , encoder_outputs=snake_case__ , ) with self.subTest("JIT Enabled" ): lowercase__ : Any= decode_jitted(**snake_case__ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowercase__ : Optional[int]= decode_jitted(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) ) for jitted_output, output in zip(snake_case__ , snake_case__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: lowercase__ : Optional[Any]= model_class_name.from_pretrained("google/pegasus-large" , from_pt=snake_case__ ) lowercase__ : List[str]= np.ones((1, 1) ) lowercase__ : List[Any]= model(snake_case__ ) self.assertIsNotNone(snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) lowercase__ : Any= PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) lowercase__ : Any= [ " 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!\" ", ] lowercase__ : Dict= [ "California's largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.", ] lowercase__ : int= tokenizer(snake_case__ , return_tensors="np" , truncation=snake_case__ , max_length=512 , padding=snake_case__ ) lowercase__ : List[str]= model.generate(**snake_case__ , num_beams=2 ).sequences lowercase__ : Union[str, Any]= tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) assert tgt_text == decoded
705
"""simple docstring""" def lowercase__(A ) ->list: """simple docstring""" if n_term == "": return [] lowercase__ : list= [] for temp in range(int(A ) ): series.append(f'''1/{temp + 1}''' if series else "1" ) return series if __name__ == "__main__": a : Dict = input("""Enter the last number (nth term) of the Harmonic Series""") print("""Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n""") print(harmonic_series(nth_term))
85
0
"""simple docstring""" def lowercase__(A ) ->Tuple: """simple docstring""" for i in range(0 , A ): for _ in range(0 , n - i - 1 ): # printing spaces print(" " , end="" ) for _ in range(0 , i + 1 ): # printing stars print("* " , end="" ) print() def lowercase__(A ) ->Tuple: """simple docstring""" for i in range(A , 0 , -1 ): for _ in range(A , 0 , -1 ): # printing stars print("* " , end="" ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(" " , end="" ) def lowercase__(A ) ->Dict: """simple docstring""" if n <= 0: print(" ... .... nothing printing :(" ) return floyd(A ) # upper half reverse_floyd(A ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a : List[Any] = 1 while K: a : int = int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a : List[str] = int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
706
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a : int = logging.get_logger(__name__) a : str = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "big_bird" def __init__( self , snake_case__=50358 , snake_case__=768 , snake_case__=12 , snake_case__=12 , snake_case__=3072 , snake_case__="gelu_new" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=4096 , snake_case__=2 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=True , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=66 , snake_case__="block_sparse" , snake_case__=True , snake_case__=False , snake_case__=64 , snake_case__=3 , snake_case__=None , **snake_case__ , ): '''simple docstring''' super().__init__( pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , sep_token_id=snake_case__ , **snake_case__ , ) lowercase__ : Dict= vocab_size lowercase__ : Optional[int]= max_position_embeddings lowercase__ : List[Any]= hidden_size lowercase__ : List[str]= num_hidden_layers lowercase__ : List[str]= num_attention_heads lowercase__ : Optional[int]= intermediate_size lowercase__ : Optional[int]= hidden_act lowercase__ : Tuple= hidden_dropout_prob lowercase__ : int= attention_probs_dropout_prob lowercase__ : int= initializer_range lowercase__ : List[Any]= type_vocab_size lowercase__ : Union[str, Any]= layer_norm_eps lowercase__ : Optional[Any]= use_cache lowercase__ : Union[str, Any]= rescale_embeddings lowercase__ : Union[str, Any]= attention_type lowercase__ : Any= use_bias lowercase__ : List[Any]= block_size lowercase__ : Optional[Any]= num_random_blocks lowercase__ : Optional[int]= classifier_dropout class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): '''simple docstring''' if self.task == "multiple-choice": lowercase__ : List[Any]= {0: "batch", 1: "choice", 2: "sequence"} else: lowercase__ : Tuple= {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
85
0
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration a : Union[str, Any] = HfArgumentParser(InitializationArguments) a : str = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization a : Optional[int] = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks a : Any = { """vocab_size""": len(tokenizer), """scale_attn_by_inverse_layer_idx""": True, """reorder_and_upcast_attn""": True, } # Load model config (GPT-2 large in this case) a : str = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config a : Tuple = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
707
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
85
0
a : Dict = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] a : str = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] a : List[Any] = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] a : List[str] = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] a : int = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] a : Dict = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] a : Optional[int] = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] a : Dict = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
708
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def lowercase__(A , A ) ->List[Any]: """simple docstring""" lowercase__ : str= [] for part_id in partition_order: lowercase__ : int= df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(A ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->str: """simple docstring""" lowercase__ : Optional[Any]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Tuple= spark.range(100 ).repartition(1 ) lowercase__ : Dict= Spark(A ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Tuple: """simple docstring""" lowercase__ : Union[str, Any]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Dict= spark.range(10 ).repartition(2 ) lowercase__ : Optional[Any]= [1, 0] lowercase__ : List[str]= _generate_iterable_examples(A , A ) # Reverse the partitions. lowercase__ : int= _get_expected_row_ids_and_row_dicts_for_partition_order(A , A ) for i, (row_id, row_dict) in enumerate(generate_fn() ): lowercase__, lowercase__ : Any= expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->int: """simple docstring""" lowercase__ : int= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Dict= spark.range(10 ).repartition(1 ) lowercase__ : str= SparkExamplesIterable(A ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(A ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->str: """simple docstring""" lowercase__ : List[str]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : int= spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("numpy.random.Generator" ) as generator_mock: lowercase__ : Optional[Any]= lambda A : x.reverse() lowercase__ : Tuple= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [2, 1, 0] ) lowercase__ : List[str]= SparkExamplesIterable(A ).shuffle_data_sources(A ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : str= expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Any: """simple docstring""" lowercase__ : Dict= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Union[str, Any]= spark.range(20 ).repartition(4 ) # Partitions 0 and 2 lowercase__ : Optional[int]= SparkExamplesIterable(A ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 lowercase__ : Union[str, Any]= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [0, 2] ) for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : Tuple= expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 lowercase__ : Tuple= SparkExamplesIterable(A ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 lowercase__ : List[Any]= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [1, 3] ) for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : Dict= expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Tuple: """simple docstring""" lowercase__ : Any= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Tuple= spark.range(100 ).repartition(1 ) lowercase__ : Optional[int]= Spark(A ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
85
0
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) a : int = logging.getLogger(__name__) a : Optional[int] = """Hello world! cécé herlolip""" a : List[str] = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowercase__(A , A ) ->Any: """simple docstring""" lowercase__ : List[Any]= BertAbsConfig( temp_dir="." , finetune_bert=A , large=A , share_emb=A , use_bert_emb=A , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2_048 , dec_dropout=0.2 , ) lowercase__ : Optional[Any]= torch.load(A , lambda A , A : storage ) lowercase__ : Dict= AbsSummarizer(A , torch.device("cpu" ) , A ) original.eval() lowercase__ : Union[str, Any]= BertAbsSummarizer(A , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) lowercase__ : Union[str, Any]= BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs lowercase__ : str= tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(A )) ) lowercase__ : List[Any]= torch.tensor(A ).unsqueeze(0 ) lowercase__ : Tuple= tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(A )) ) lowercase__ : int= torch.tensor(A ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass lowercase__ : Optional[Any]= encoder_input_ids lowercase__ : Union[str, Any]= decoder_input_ids lowercase__ : Tuple= None lowercase__ : List[str]= None lowercase__ : Dict= None lowercase__ : Any= None lowercase__ : Dict= None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical lowercase__ : List[str]= original(A , A , A , A , A , A , A )[0] lowercase__ : Optional[int]= original.generator(A ) lowercase__ : int= new_model( A , A , A , A , A )[0] lowercase__ : List[str]= new_model.generator(A ) lowercase__ : Any= torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(A ) ) lowercase__ : Optional[Any]= torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(A ) ) lowercase__ : Dict= torch.allclose(A , A , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": a : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) a : Union[str, Any] = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
709
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=False , snake_case__=False , snake_case__=False , snake_case__=2 , snake_case__=99 , snake_case__=0 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=512 , snake_case__=12 , snake_case__=2 , snake_case__=0.02 , snake_case__=3 , snake_case__=4 , snake_case__="last" , snake_case__=None , snake_case__=None , ): '''simple docstring''' lowercase__ : Optional[int]= parent lowercase__ : Tuple= batch_size lowercase__ : Tuple= seq_length lowercase__ : str= is_training lowercase__ : str= use_input_lengths lowercase__ : Any= use_token_type_ids lowercase__ : List[Any]= use_labels lowercase__ : Optional[int]= gelu_activation lowercase__ : str= sinusoidal_embeddings lowercase__ : List[str]= causal lowercase__ : Any= asm lowercase__ : Optional[int]= n_langs lowercase__ : Union[str, Any]= vocab_size lowercase__ : int= n_special lowercase__ : Any= hidden_size lowercase__ : int= num_hidden_layers lowercase__ : List[str]= num_attention_heads lowercase__ : List[str]= hidden_dropout_prob lowercase__ : str= attention_probs_dropout_prob lowercase__ : Any= max_position_embeddings lowercase__ : List[Any]= type_vocab_size lowercase__ : int= type_sequence_label_size lowercase__ : Any= initializer_range lowercase__ : Optional[int]= num_labels lowercase__ : Union[str, Any]= num_choices lowercase__ : List[Any]= summary_type lowercase__ : Optional[int]= use_proj lowercase__ : int= scope def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : Dict= random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ : Tuple= None if self.use_input_lengths: lowercase__ : List[Any]= ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowercase__ : Tuple= None if self.use_token_type_ids: lowercase__ : Any= ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowercase__ : str= None lowercase__ : Tuple= None lowercase__ : Dict= None if self.use_labels: lowercase__ : Optional[Any]= ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Optional[Any]= ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase__ : Tuple= ids_tensor([self.batch_size] , 2 ).float() lowercase__ : Tuple= ids_tensor([self.batch_size] , self.num_choices ) lowercase__ : List[Any]= self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase_ ( self ): '''simple docstring''' return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : Any= FlaubertModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : str= model(snake_case__ , lengths=snake_case__ , langs=snake_case__ ) lowercase__ : str= model(snake_case__ , langs=snake_case__ ) lowercase__ : Any= model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : str= FlaubertWithLMHeadModel(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Optional[Any]= model(snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : str= FlaubertForQuestionAnsweringSimple(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[str]= model(snake_case__ ) lowercase__ : Dict= model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[Any]= FlaubertForQuestionAnswering(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= model(snake_case__ ) lowercase__ : Any= model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , p_mask=snake_case__ , ) lowercase__ : List[str]= model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , ) ((lowercase__), ) : Optional[Any]= result_with_labels.to_tuple() lowercase__ : Union[str, Any]= model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) ((lowercase__), ) : List[Any]= result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[str]= FlaubertForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Optional[Any]= model(snake_case__ ) lowercase__ : Optional[Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[Any]= self.num_labels lowercase__ : Union[str, Any]= FlaubertForTokenClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : int= model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : int= self.num_choices lowercase__ : str= FlaubertForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : int= token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : str= input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : Any= model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.prepare_config_and_inputs() ( ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ) : Any= config_and_inputs lowercase__ : Tuple= { "input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths, "attention_mask": input_mask, } return config, inputs_dict @require_torch class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) __lowerCamelCase = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__=False ): '''simple docstring''' lowercase__ : Tuple= super()._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": lowercase__ : List[Any]= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) lowercase__ : List[str]= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) return inputs_dict def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= FlaubertModelTester(self ) lowercase__ : List[str]= ConfigTester(self , config_class=snake_case__ , emb_dim=37 ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : List[str]= FlaubertModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__, lowercase__ : Optional[Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return lowercase__ : int= True lowercase__ : List[Any]= model_class(config=snake_case__ ) lowercase__ : str= self._prepare_for_class(snake_case__ , snake_case__ ) lowercase__ : Dict= torch.jit.trace( snake_case__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(snake_case__ , os.path.join(snake_case__ , "traced_model.pt" ) ) lowercase__ : str= torch.jit.load(os.path.join(snake_case__ , "traced_model.pt" ) , map_location=snake_case__ ) loaded(inputs_dict["input_ids"].to(snake_case__ ) , inputs_dict["attention_mask"].to(snake_case__ ) ) @require_torch class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= FlaubertModel.from_pretrained("flaubert/flaubert_base_cased" ) lowercase__ : Tuple= torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): lowercase__ : Optional[int]= model(snake_case__ )[0] lowercase__ : Optional[int]= torch.Size((1, 11, 768) ) self.assertEqual(output.shape , snake_case__ ) lowercase__ : Dict= torch.tensor( [[[-2.62_51, -1.42_98, -0.02_27], [-2.85_10, -1.63_87, 0.22_58], [-2.81_14, -1.18_32, -0.30_66]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) )
85
0
"""simple docstring""" from __future__ import annotations import requests def lowercase__(A ): """simple docstring""" lowercase__ : Optional[Any]= f'''https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty''' return requests.get(A ).json() def lowercase__(A = 10 ): """simple docstring""" lowercase__ : Union[str, Any]= "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" lowercase__ : Optional[Any]= requests.get(A ).json()[:max_stories] return [get_hackernews_story(A ) for story_id in story_ids] def lowercase__(A = 10 ): """simple docstring""" lowercase__ : Optional[Any]= hackernews_top_stories(A ) return "\n".join("* [{title}]({url})".format(**A ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = None class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 2 @register_to_config def __init__( self , snake_case__ = 0.02 , snake_case__ = 100 , snake_case__ = 1.0_07 , snake_case__ = 80 , snake_case__ = 0.05 , snake_case__ = 50 , ): '''simple docstring''' # standard deviation of the initial noise distribution lowercase__ : int= sigma_max # setable values lowercase__ : int= None lowercase__ : np.IntTensor= None lowercase__ : torch.FloatTensor= None # sigma(t_i) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' return sample def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' lowercase__ : List[Any]= num_inference_steps lowercase__ : Any= np.arange(0 , self.num_inference_steps )[::-1].copy() lowercase__ : Tuple= torch.from_numpy(snake_case__ ).to(snake_case__ ) lowercase__ : Union[str, Any]= [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] lowercase__ : int= torch.tensor(snake_case__ , dtype=torch.floataa , device=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ = None ): '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: lowercase__ : Optional[Any]= min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: lowercase__ : str= 0 # sample eps ~ N(0, S_noise^2 * I) lowercase__ : List[Any]= self.config.s_noise * randn_tensor(sample.shape , generator=snake_case__ ).to(sample.device ) lowercase__ : str= sigma + gamma * sigma lowercase__ : Any= sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = True , ): '''simple docstring''' lowercase__ : Union[str, Any]= sample_hat + sigma_hat * model_output lowercase__ : Optional[int]= (sample_hat - pred_original_sample) / sigma_hat lowercase__ : Optional[Any]= sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=snake_case__ , derivative=snake_case__ , pred_original_sample=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = True , ): '''simple docstring''' lowercase__ : int= sample_prev + sigma_prev * model_output lowercase__ : Optional[int]= (sample_prev - pred_original_sample) / sigma_prev lowercase__ : Optional[Any]= sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=snake_case__ , derivative=snake_case__ , pred_original_sample=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' raise NotImplementedError()
85
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a : Any = logging.get_logger(__name__) a : Tuple = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "gpt_neox_japanese" def __init__( self , snake_case__=32000 , snake_case__=2560 , snake_case__=32 , snake_case__=32 , snake_case__=4 , snake_case__="gelu" , snake_case__=1.00 , snake_case__=10000 , snake_case__=2048 , snake_case__=0.02 , snake_case__=1e-5 , snake_case__=True , snake_case__=31996 , snake_case__=31999 , snake_case__=0.1 , snake_case__=0.0 , **snake_case__ , ): '''simple docstring''' super().__init__(bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ ) lowercase__ : str= vocab_size lowercase__ : Optional[Any]= max_position_embeddings lowercase__ : Optional[Any]= hidden_size lowercase__ : Tuple= num_hidden_layers lowercase__ : List[Any]= num_attention_heads lowercase__ : Tuple= intermediate_multiple_size lowercase__ : int= hidden_act lowercase__ : Dict= rotary_pct lowercase__ : Optional[Any]= rotary_emb_base lowercase__ : str= initializer_range lowercase__ : str= layer_norm_eps lowercase__ : Optional[int]= use_cache lowercase__ : Tuple= attention_dropout lowercase__ : List[Any]= hidden_dropout
711
"""simple docstring""" from ....utils import logging a : List[str] = logging.get_logger(__name__) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__=None , snake_case__=2048 ): '''simple docstring''' lowercase__ : Dict= config.__dict__ lowercase__ : str= modal_hidden_size if num_labels: lowercase__ : List[str]= num_labels
85
0
"""simple docstring""" from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowercase__() ->tuple[list[int], int]: """simple docstring""" lowercase__ : Optional[int]= [randint(-1_000 , 1_000 ) for i in range(10 )] lowercase__ : str= randint(-5_000 , 5_000 ) return (arr, r) a : Optional[int] = make_dataset() def lowercase__(A , A ) ->tuple[int, ...]: """simple docstring""" for triplet in permutations(A , 3 ): if sum(A ) == target: return tuple(sorted(A ) ) return (0, 0, 0) def lowercase__(A , A ) ->tuple[int, int, int]: """simple docstring""" arr.sort() lowercase__ : Optional[int]= len(A ) for i in range(n - 1 ): lowercase__ : int= i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowercase__() ->tuple[float, float]: """simple docstring""" lowercase__ : List[str]= "\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n" lowercase__ : Union[str, Any]= "\ntriplet_sum1(*dataset)\n" lowercase__ : Union[str, Any]= "\ntriplet_sum2(*dataset)\n" lowercase__ : List[str]= repeat(setup=A , stmt=A , repeat=5 , number=10_000 ) lowercase__ : Tuple= repeat(setup=A , stmt=A , repeat=5 , number=10_000 ) return (min(A ), min(A )) if __name__ == "__main__": from doctest import testmod testmod() a : Any = solution_times() print(F"""The time for naive implementation is {times[0]}.""") print(F"""The time for optimized implementation is {times[1]}.""")
712
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def lowercase__(A ) ->int: """simple docstring""" lowercase__ : Optional[int]= [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def lowercase__(A , A ) ->Any: """simple docstring""" lowercase__ : Any= [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def lowercase__(A ) ->List[Any]: """simple docstring""" lowercase__ : Dict= [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', "stage2.cls_token") ) return token def lowercase__() ->Union[str, Any]: """simple docstring""" lowercase__ : Dict= [] head.append(("layernorm.weight", "norm.weight") ) head.append(("layernorm.bias", "norm.bias") ) head.append(("classifier.weight", "head.weight") ) head.append(("classifier.bias", "head.bias") ) return head def lowercase__(A , A , A , A ) ->Optional[int]: """simple docstring""" lowercase__ : List[str]= "imagenet-1k-id2label.json" lowercase__ : List[str]= 1_000 lowercase__ : Tuple= "huggingface/label-files" lowercase__ : int= num_labels lowercase__ : int= json.load(open(cached_download(hf_hub_url(A , A , repo_type="dataset" ) ) , "r" ) ) lowercase__ : str= {int(A ): v for k, v in idalabel.items()} lowercase__ : Optional[int]= idalabel lowercase__ : Union[str, Any]= {v: k for k, v in idalabel.items()} lowercase__ : Tuple= CvtConfig(num_labels=A , idalabel=A , labelaid=A ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13": lowercase__ : int= [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21": lowercase__ : Union[str, Any]= [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowercase__ : Optional[Any]= [2, 2, 20] lowercase__ : Optional[Any]= [3, 12, 16] lowercase__ : List[str]= [192, 768, 1_024] lowercase__ : List[str]= CvtForImageClassification(A ) lowercase__ : Any= AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" ) lowercase__ : Dict= image_size lowercase__ : int= torch.load(A , map_location=torch.device("cpu" ) ) lowercase__ : Optional[Any]= OrderedDict() lowercase__ : Tuple= [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowercase__ : Optional[int]= list_of_state_dict + cls_token(A ) lowercase__ : List[str]= list_of_state_dict + embeddings(A ) for cnt in range(config.depth[idx] ): lowercase__ : Dict= list_of_state_dict + attention(A , A ) lowercase__ : Optional[Any]= list_of_state_dict + final() for gg in list_of_state_dict: print(A ) for i in range(len(A ) ): lowercase__ : str= original_weights[list_of_state_dict[i][1]] model.load_state_dict(A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": a : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=384, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=r"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) a : Optional[int] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
85
0
"""simple docstring""" import torch from diffusers import DiffusionPipeline class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__() self.register_modules(unet=snake_case__ , scheduler=snake_case__ ) def __call__( self ): '''simple docstring''' lowercase__ : Optional[Any]= torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) lowercase__ : List[str]= 1 lowercase__ : int= self.unet(snake_case__ , snake_case__ ).sample lowercase__ : Optional[Any]= self.scheduler.step(snake_case__ , snake_case__ , snake_case__ ).prev_sample lowercase__ : List[Any]= scheduler_output - scheduler_output + torch.ones_like(snake_case__ ) return result
713
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = 42 def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__() self.register_modules(unet=snake_case__ , scheduler=snake_case__ ) @torch.no_grad() def __call__( self , snake_case__ = 1 , snake_case__ = 2000 , snake_case__ = None , snake_case__ = "pil" , snake_case__ = True , **snake_case__ , ): '''simple docstring''' lowercase__ : Optional[Any]= self.unet.config.sample_size lowercase__ : Dict= (batch_size, 3, img_size, img_size) lowercase__ : List[Any]= self.unet lowercase__ : Tuple= randn_tensor(snake_case__ , generator=snake_case__ ) * self.scheduler.init_noise_sigma lowercase__ : Tuple= sample.to(self.device ) self.scheduler.set_timesteps(snake_case__ ) self.scheduler.set_sigmas(snake_case__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowercase__ : Optional[Any]= self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): lowercase__ : List[Any]= self.unet(snake_case__ , snake_case__ ).sample lowercase__ : List[Any]= self.scheduler.step_correct(snake_case__ , snake_case__ , generator=snake_case__ ).prev_sample # prediction step lowercase__ : List[str]= model(snake_case__ , snake_case__ ).sample lowercase__ : Tuple= self.scheduler.step_pred(snake_case__ , snake_case__ , snake_case__ , generator=snake_case__ ) lowercase__, lowercase__ : Tuple= output.prev_sample, output.prev_sample_mean lowercase__ : List[str]= sample_mean.clamp(0 , 1 ) lowercase__ : Union[str, Any]= sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowercase__ : str= self.numpy_to_pil(snake_case__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=snake_case__ )
85
0
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__ , snake_case__=100 , snake_case__=13 , snake_case__=30 , snake_case__=2 , snake_case__=3 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=4 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , snake_case__=[0, 1, 2, 3] , ): '''simple docstring''' lowercase__ : Any= parent lowercase__ : Tuple= 100 lowercase__ : Optional[int]= batch_size lowercase__ : Optional[int]= image_size lowercase__ : List[Any]= patch_size lowercase__ : Union[str, Any]= num_channels lowercase__ : Tuple= is_training lowercase__ : Union[str, Any]= use_labels lowercase__ : Any= hidden_size lowercase__ : Optional[int]= num_hidden_layers lowercase__ : List[str]= num_attention_heads lowercase__ : int= intermediate_size lowercase__ : Optional[int]= hidden_act lowercase__ : Dict= hidden_dropout_prob lowercase__ : Optional[Any]= attention_probs_dropout_prob lowercase__ : Optional[Any]= type_sequence_label_size lowercase__ : str= initializer_range lowercase__ : Union[str, Any]= scope lowercase__ : Union[str, Any]= out_indices lowercase__ : List[str]= num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase__ : Tuple= (image_size // patch_size) ** 2 lowercase__ : Any= num_patches + 1 def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : int= None lowercase__ : Union[str, Any]= None if self.use_labels: lowercase__ : Tuple= ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : str= ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowercase__ : str= self.get_config() return config, pixel_values, labels, pixel_labels def UpperCAmelCase_ ( self ): '''simple docstring''' return BeitConfig( vocab_size=self.vocab_size , 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=snake_case__ , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Optional[int]= BeitModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[str]= model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : int= BeitForMaskedImageModeling(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Optional[Any]= self.type_sequence_label_size lowercase__ : int= BeitForImageClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase__ : Optional[Any]= 1 lowercase__ : int= BeitForImageClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ : List[Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Dict= self.num_labels lowercase__ : str= BeitForSemanticSegmentation(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[str]= model(snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) lowercase__ : Union[str, Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.prepare_config_and_inputs() lowercase__ : str= config_and_inputs lowercase__ : Optional[int]= {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __lowerCamelCase = ( { "feature-extraction": BeitModel, "image-classification": BeitForImageClassification, "image-segmentation": BeitForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= BeitModelTester(self ) lowercase__ : List[str]= ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="BEiT does not use inputs_embeds" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Optional[int]= model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : str= model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Optional[Any]= model_class(snake_case__ ) lowercase__ : List[Any]= inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : List[str]= [*signature.parameters.keys()] lowercase__ : Optional[int]= ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' if not self.model_tester.is_training: return lowercase__ : Any= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple= True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case__ ), BeitForMaskedImageModeling]: continue lowercase__ : str= model_class(snake_case__ ) model.to(snake_case__ ) model.train() lowercase__ : Tuple= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) lowercase__ : Union[str, Any]= model(**snake_case__ ).loss loss.backward() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return lowercase__ : Optional[Any]= False lowercase__ : Any= True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case__ ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue lowercase__ : int= model_class(snake_case__ ) model.gradient_checkpointing_enable() model.to(snake_case__ ) model.train() lowercase__ : Union[str, Any]= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) lowercase__ : Tuple= model(**snake_case__ ).loss loss.backward() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple= _config_zero_init(snake_case__ ) for model_class in self.all_model_classes: lowercase__ : List[Any]= model_class(config=snake_case__ ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : Tuple= BeitModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def lowercase__() ->Union[str, Any]: """simple docstring""" lowercase__ : Dict= Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): '''simple docstring''' return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" ).to(snake_case__ ) lowercase__ : Optional[Any]= self.default_image_processor lowercase__ : Dict= prepare_img() lowercase__ : Optional[Any]= image_processor(images=snake_case__ , return_tensors="pt" ).pixel_values.to(snake_case__ ) # prepare bool_masked_pos lowercase__ : str= torch.ones((1, 196) , dtype=torch.bool ).to(snake_case__ ) # forward pass with torch.no_grad(): lowercase__ : int= model(pixel_values=snake_case__ , bool_masked_pos=snake_case__ ) lowercase__ : Any= outputs.logits # verify the logits lowercase__ : str= torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape , snake_case__ ) lowercase__ : List[Any]= torch.tensor( [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , snake_case__ , atol=1e-2 ) ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" ).to(snake_case__ ) lowercase__ : Tuple= self.default_image_processor lowercase__ : int= prepare_img() lowercase__ : Tuple= image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): lowercase__ : Union[str, Any]= model(**snake_case__ ) lowercase__ : Any= outputs.logits # verify the logits lowercase__ : Union[str, Any]= torch.Size((1, 1000) ) self.assertEqual(logits.shape , snake_case__ ) lowercase__ : int= torch.tensor([-1.23_85, -1.09_87, -1.01_08] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 ) ) lowercase__ : str= 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" ).to( snake_case__ ) lowercase__ : List[str]= self.default_image_processor lowercase__ : str= prepare_img() lowercase__ : Optional[int]= image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): lowercase__ : int= model(**snake_case__ ) lowercase__ : Any= outputs.logits # verify the logits lowercase__ : List[str]= torch.Size((1, 21841) ) self.assertEqual(logits.shape , snake_case__ ) lowercase__ : Tuple= torch.tensor([1.68_81, -0.27_87, 0.59_01] ).to(snake_case__ ) self.assertTrue(torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 ) ) lowercase__ : Tuple= 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) lowercase__ : Optional[int]= model.to(snake_case__ ) lowercase__ : Tuple= BeitImageProcessor(do_resize=snake_case__ , size=640 , do_center_crop=snake_case__ ) lowercase__ : str= load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) lowercase__ : List[Any]= Image.open(ds[0]["file"] ) lowercase__ : int= image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): lowercase__ : Tuple= model(**snake_case__ ) lowercase__ : List[str]= outputs.logits # verify the logits lowercase__ : Dict= torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape , snake_case__ ) lowercase__ : Tuple= version.parse(PIL.__version__ ) < version.parse("9.0.0" ) if is_pillow_less_than_a: lowercase__ : List[Any]= torch.tensor( [ [[-4.92_25, -2.39_54, -3.05_22], [-2.88_22, -1.00_46, -1.75_61], [-2.95_49, -1.32_28, -2.13_47]], [[-5.81_68, -3.41_29, -4.07_78], [-3.86_51, -2.22_14, -3.02_77], [-3.83_56, -2.46_43, -3.35_35]], [[-0.00_78, 3.99_52, 4.07_54], [2.98_56, 4.69_44, 5.00_35], [3.24_13, 4.78_13, 4.99_69]], ] , device=snake_case__ , ) else: lowercase__ : Optional[Any]= torch.tensor( [ [[-4.89_60, -2.36_88, -3.03_55], [-2.84_78, -0.98_36, -1.74_18], [-2.94_49, -1.33_32, -2.14_56]], [[-5.80_81, -3.41_24, -4.10_06], [-3.85_61, -2.20_81, -3.03_23], [-3.83_65, -2.46_01, -3.36_69]], [[-0.03_09, 3.98_68, 4.05_40], [2.96_40, 4.68_77, 4.99_76], [3.20_81, 4.76_90, 4.99_42]], ] , device=snake_case__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) lowercase__ : int= model.to(snake_case__ ) lowercase__ : Union[str, Any]= BeitImageProcessor(do_resize=snake_case__ , size=640 , do_center_crop=snake_case__ ) lowercase__ : int= load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) lowercase__ : str= Image.open(ds[0]["file"] ) lowercase__ : Optional[int]= image_processor(images=snake_case__ , return_tensors="pt" ).to(snake_case__ ) # forward pass with torch.no_grad(): lowercase__ : Optional[Any]= model(**snake_case__ ) lowercase__ : Optional[int]= outputs.logits.detach().cpu() lowercase__ : List[str]= image_processor.post_process_semantic_segmentation(outputs=snake_case__ , target_sizes=[(500, 300)] ) lowercase__ : List[str]= torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , snake_case__ ) lowercase__ : str= image_processor.post_process_semantic_segmentation(outputs=snake_case__ ) lowercase__ : str= torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape , snake_case__ )
714
"""simple docstring""" def lowercase__(A ) ->list[int]: """simple docstring""" lowercase__ : List[str]= len(A ) for i in range(A ): for j in range(i + 1 , A ): if numbers[j] < numbers[i]: lowercase__, lowercase__ : List[str]= numbers[j], numbers[i] return numbers if __name__ == "__main__": a : Dict = input("""Enter numbers separated by a comma:\n""").strip() a : List[str] = [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
85
0
"""simple docstring""" import qiskit def lowercase__(A = 2 ) ->qiskit.result.counts.Counts: lowercase__ : Any= qubits # Using Aer's simulator lowercase__ : Any= qiskit.Aer.get_backend("aer_simulator" ) # Creating a Quantum Circuit acting on the q register lowercase__ : Any= qiskit.QuantumCircuit(A , A ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , A ): # Adding CX (CNOT) gate circuit.cx(i - 1 , A ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(A ) ) , list(range(A ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator lowercase__ : Union[str, Any]= qiskit.execute(A , A , shots=1_000 ) return job.result().get_counts(A ) if __name__ == "__main__": print(F"""Total count for various states are: {quantum_entanglement(3)}""")
715
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def lowercase__(A ) ->bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase__() ->Iterator[int]: """simple docstring""" lowercase__ : Union[str, Any]= 2 while True: if is_prime(A ): yield num num += 1 def lowercase__(A = 2_000_000 ) ->int: """simple docstring""" return sum(takewhile(lambda A : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = 42 def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__() self.register_modules(unet=snake_case__ , scheduler=snake_case__ ) @torch.no_grad() def __call__( self , snake_case__ = 1 , snake_case__ = 2000 , snake_case__ = None , snake_case__ = "pil" , snake_case__ = True , **snake_case__ , ): '''simple docstring''' lowercase__ : Optional[Any]= self.unet.config.sample_size lowercase__ : Dict= (batch_size, 3, img_size, img_size) lowercase__ : List[Any]= self.unet lowercase__ : Tuple= randn_tensor(snake_case__ , generator=snake_case__ ) * self.scheduler.init_noise_sigma lowercase__ : Tuple= sample.to(self.device ) self.scheduler.set_timesteps(snake_case__ ) self.scheduler.set_sigmas(snake_case__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowercase__ : Optional[Any]= self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): lowercase__ : List[Any]= self.unet(snake_case__ , snake_case__ ).sample lowercase__ : List[Any]= self.scheduler.step_correct(snake_case__ , snake_case__ , generator=snake_case__ ).prev_sample # prediction step lowercase__ : List[str]= model(snake_case__ , snake_case__ ).sample lowercase__ : Tuple= self.scheduler.step_pred(snake_case__ , snake_case__ , snake_case__ , generator=snake_case__ ) lowercase__ : Tuple= output.prev_sample, output.prev_sample_mean lowercase__ : List[str]= sample_mean.clamp(0 , 1 ) lowercase__ : Union[str, Any]= sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowercase__ : str= self.numpy_to_pil(snake_case__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=snake_case__ )
716
"""simple docstring""" def lowercase__(A ) ->bool: """simple docstring""" lowercase__ : Tuple= (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowercase__(A = 5_000 ) ->int: """simple docstring""" lowercase__ : str= [(i * (3 * i - 1)) // 2 for i in range(1 , A )] for i, pentagonal_i in enumerate(A ): for j in range(A , len(A ) ): lowercase__ : List[Any]= pentagonal_nums[j] lowercase__ : int= pentagonal_i + pentagonal_j lowercase__ : Optional[int]= pentagonal_j - pentagonal_i if is_pentagonal(A ) and is_pentagonal(A ): return b return -1 if __name__ == "__main__": print(F"""{solution() = }""")
85
0
"""simple docstring""" from __future__ import annotations def lowercase__(A ) ->list[int]: # This function is recursive """simple docstring""" lowercase__ : int= len(A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else lowercase__ : str= array[0] lowercase__ : Optional[Any]= False lowercase__ : Any= 1 lowercase__ : list[int]= [] while not is_found and i < array_length: if array[i] < pivot: lowercase__ : Union[str, Any]= True lowercase__ : List[str]= [element for element in array[i:] if element >= array[i]] lowercase__ : Union[str, Any]= longest_subsequence(A ) if len(A ) > len(A ): lowercase__ : List[str]= temp_array else: i += 1 lowercase__ : List[str]= [element for element in array[1:] if element >= pivot] lowercase__ : List[str]= [pivot, *longest_subsequence(A )] if len(A ) > len(A ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
717
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a : List[str] = logging.get_logger(__name__) a : Union[str, Any] = { """google/pix2struct-textcaps-base""": ( """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json""" ), } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct_text_model" __lowerCamelCase = ["past_key_values"] __lowerCamelCase = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , snake_case__=50244 , snake_case__=768 , snake_case__=64 , snake_case__=2048 , snake_case__=12 , snake_case__=12 , snake_case__=32 , snake_case__=128 , snake_case__=0.1 , snake_case__=1e-6 , snake_case__=1.0 , snake_case__="gelu_new" , snake_case__=0 , snake_case__=False , snake_case__=0 , snake_case__=1 , snake_case__=False , snake_case__=True , **snake_case__ , ): '''simple docstring''' lowercase__ : int= vocab_size lowercase__ : Optional[Any]= hidden_size lowercase__ : Tuple= d_kv lowercase__ : Optional[int]= d_ff lowercase__ : Any= num_layers lowercase__ : Dict= num_heads lowercase__ : List[Any]= relative_attention_num_buckets lowercase__ : Optional[Any]= relative_attention_max_distance lowercase__ : Dict= dropout_rate lowercase__ : Tuple= layer_norm_epsilon lowercase__ : str= initializer_factor lowercase__ : Any= use_cache lowercase__ : Optional[int]= eos_token_id lowercase__ : str= decoder_start_token_id # for backwards compatibility lowercase__ : Optional[Any]= dense_act_fn super().__init__( pad_token_id=snake_case__ , eos_token_id=snake_case__ , decoder_start_token_id=snake_case__ , tie_word_embeddings=snake_case__ , is_decoder=snake_case__ , **snake_case__ , ) @classmethod def UpperCAmelCase_ ( cls , snake_case__ , **snake_case__ ): '''simple docstring''' cls._set_token_in_kwargs(snake_case__ ) lowercase__, lowercase__ : str= cls.get_config_dict(snake_case__ , **snake_case__ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("model_type" ) == "pix2struct": lowercase__ : str= config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(snake_case__ , **snake_case__ ) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct_vision_model" def __init__( self , snake_case__=768 , snake_case__=768 , snake_case__=2048 , snake_case__=64 , snake_case__=12 , snake_case__=12 , snake_case__="gelu_new" , snake_case__=1e-6 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=1e-10 , snake_case__=1.0 , snake_case__=4096 , snake_case__=32 , snake_case__=128 , **snake_case__ , ): '''simple docstring''' super().__init__(**snake_case__ ) lowercase__ : Tuple= hidden_size lowercase__ : Tuple= patch_embed_hidden_size lowercase__ : Optional[Any]= d_ff lowercase__ : Dict= dropout_rate lowercase__ : Any= num_hidden_layers lowercase__ : Optional[int]= num_attention_heads lowercase__ : Dict= initializer_range lowercase__ : Tuple= initializer_factor lowercase__ : Tuple= attention_dropout lowercase__ : Optional[Any]= layer_norm_eps lowercase__ : List[Any]= dense_act_fn lowercase__ : str= seq_len lowercase__ : List[str]= relative_attention_num_buckets lowercase__ : Union[str, Any]= relative_attention_max_distance lowercase__ : Dict= d_kv @classmethod def UpperCAmelCase_ ( cls , snake_case__ , **snake_case__ ): '''simple docstring''' cls._set_token_in_kwargs(snake_case__ ) lowercase__, lowercase__ : int= cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("model_type" ) == "pix2struct": lowercase__ : Union[str, Any]= 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(snake_case__ , **snake_case__ ) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct" __lowerCamelCase = True def __init__( self , snake_case__=None , snake_case__=None , snake_case__=1.0 , snake_case__=0.02 , snake_case__=False , snake_case__=False , snake_case__=True , **snake_case__ , ): '''simple docstring''' super().__init__(tie_word_embeddings=snake_case__ , is_encoder_decoder=snake_case__ , **snake_case__ ) if text_config is None: lowercase__ : List[Any]= {} logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values." ) if vision_config is None: lowercase__ : str= {} logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values." ) lowercase__ : str= PixaStructTextConfig(**snake_case__ ) lowercase__ : Dict= PixaStructVisionConfig(**snake_case__ ) lowercase__ : int= self.text_config.decoder_start_token_id lowercase__ : List[Any]= self.text_config.pad_token_id lowercase__ : Any= self.text_config.eos_token_id lowercase__ : Any= initializer_factor lowercase__ : int= initializer_range lowercase__ : List[str]= self.initializer_range lowercase__ : List[str]= self.initializer_range lowercase__ : Dict= is_vqa @classmethod def UpperCAmelCase_ ( cls , snake_case__ , snake_case__ , **snake_case__ ): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= copy.deepcopy(self.__dict__ ) lowercase__ : str= self.text_config.to_dict() lowercase__ : str= self.vision_config.to_dict() lowercase__ : List[str]= self.__class__.model_type return output
85
0
"""simple docstring""" import os def lowercase__(A = "input.txt" ) ->int: """simple docstring""" with open(os.path.join(os.path.dirname(A ) , A ) ) as input_file: lowercase__ : Optional[Any]= [ [int(A ) for element in line.split("," )] for line in input_file.readlines() ] lowercase__ : Optional[Any]= len(A ) lowercase__ : Dict= len(matrix[0] ) lowercase__ : Any= [[-1 for _ in range(A )] for _ in range(A )] for i in range(A ): lowercase__ : Any= matrix[i][0] for j in range(1 , A ): for i in range(A ): lowercase__ : List[str]= minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , A ): lowercase__ : str= min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): lowercase__ : int= min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F"""{solution() = }""")
718
"""simple docstring""" 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 tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) lowercase__ : str= AutoTokenizer.from_pretrained("google/mt5-small" ) lowercase__ : Tuple= tokenizer("Hello there" , return_tensors="tf" ).input_ids lowercase__ : Optional[Any]= tokenizer("Hi I am" , return_tensors="tf" ).input_ids lowercase__ : Optional[Any]= model(snake_case__ , labels=snake_case__ ).loss lowercase__ : int= -tf.math.reduce_mean(snake_case__ ).numpy() lowercase__ : int= -21.22_81_68 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
85
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a : int = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""], """processing_trocr""": ["""TrOCRProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : int = [ """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""", """TrOCRForCausalLM""", """TrOCRPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
719
"""simple docstring""" 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( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "BridgeTowerImageProcessor" __lowerCamelCase = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) 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''' lowercase__ : Optional[int]= 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 lowercase__ : Optional[int]= self.image_processor( snake_case__ , return_tensors=snake_case__ , do_normalize=snake_case__ , do_center_crop=snake_case__ , **snake_case__ ) encoding.update(snake_case__ ) return encoding def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.tokenizer.model_input_names lowercase__ : List[Any]= self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
0
"""simple docstring""" def lowercase__(A ) ->str: """simple docstring""" return "".join(chr(ord(A ) - 32 ) if "a" <= char <= "z" else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
720
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= tempfile.mkdtemp() lowercase__ : Optional[Any]= 8 # DPR tok lowercase__ : Tuple= [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowercase__ : Any= os.path.join(self.tmpdirname , "dpr_tokenizer" ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) lowercase__ : Any= os.path.join(snake_case__ , DPR_VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) # BART tok lowercase__ : List[Any]= [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] lowercase__ : Tuple= dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) lowercase__ : Any= ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowercase__ : Tuple= {"unk_token": "<unk>"} lowercase__ : int= os.path.join(self.tmpdirname , "bart_tokenizer" ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) lowercase__ : List[str]= os.path.join(snake_case__ , BART_VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : str= os.path.join(snake_case__ , BART_VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(snake_case__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(snake_case__ ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.get_dummy_dataset() lowercase__ : Optional[Any]= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: lowercase__ : Tuple= dataset lowercase__ : Optional[int]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : Dict= self.get_dummy_dataset() lowercase__ : Tuple= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="custom" , ) if from_disk: lowercase__ : Tuple= os.path.join(self.tmpdirname , "dataset" ) lowercase__ : Optional[Any]= os.path.join(self.tmpdirname , "index.faiss" ) dataset.get_index("embeddings" ).save(os.path.join(self.tmpdirname , "index.faiss" ) ) dataset.drop_index("embeddings" ) dataset.save_to_disk(os.path.join(self.tmpdirname , "dataset" ) ) del dataset lowercase__ : List[Any]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: lowercase__ : Optional[int]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , snake_case__ ) , ) return retriever def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) lowercase__ : Optional[int]= os.path.join(self.tmpdirname , "hf_bert_base.hnswSQ8_correct_phi_128.c_index" ) dataset.save_faiss_index("embeddings" , index_file_name + ".index.dpr" ) pickle.dump(dataset["id"] , open(index_file_name + ".index_meta.dpr" , "wb" ) ) lowercase__ : int= os.path.join(self.tmpdirname , "psgs_w100.tsv.pkl" ) lowercase__ : str= {sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(snake_case__ , open(snake_case__ , "wb" ) ) lowercase__ : List[Any]= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="legacy" , index_path=self.tmpdirname , ) lowercase__ : Optional[Any]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= 1 lowercase__ : Optional[Any]= self.get_dummy_canonical_hf_index_retriever() lowercase__ : Union[str, Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[int]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: lowercase__ : Tuple= self.get_dummy_dataset() retriever.save_pretrained(snake_case__ ) lowercase__ : int= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : Any= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Tuple= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= 1 lowercase__ : Any= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) lowercase__ : Union[str, Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Any= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : int= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : Tuple= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : str= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= 1 lowercase__ : str= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) lowercase__ : List[str]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[int]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : Optional[Any]= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : int= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Union[str, Any]= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= 1 lowercase__ : int= self.get_dummy_legacy_index_retriever() lowercase__ : Optional[Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[Any]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["text", "title"] ) self.assertEqual(len(doc_dicts[0]["text"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["text"][0] , "bar" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] , "foo" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : List[Any]= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : str= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Tuple= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self ): '''simple docstring''' import torch lowercase__ : str= 1 lowercase__ : Union[str, Any]= self.get_dummy_canonical_hf_index_retriever() lowercase__ : str= [[5, 7], [10, 11]] lowercase__ : List[str]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Dict= retriever(snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ ) lowercase__, lowercase__, lowercase__ : Optional[int]= ( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertIsInstance(snake_case__ , np.ndarray ) lowercase__ : Any= retriever( snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ , return_tensors="pt" , ) lowercase__, lowercase__, lowercase__, lowercase__ : Tuple= ( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(snake_case__ , torch.Tensor ) self.assertIsInstance(snake_case__ , torch.Tensor ) self.assertIsInstance(snake_case__ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.get_dpr_ctx_encoder_tokenizer() lowercase__ : Dict= 1 lowercase__ : Any= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) retriever.set_ctx_encoder_tokenizer(snake_case__ ) lowercase__ : List[str]= [[5, 7], [10, 11]] lowercase__ : Any= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : List[Any]= retriever(snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ ) self.assertEqual( len(snake_case__ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask") ) , snake_case__ ) # check for doc token related keys in dictionary.
85
0
"""simple docstring""" 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( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "BridgeTowerImageProcessor" __lowerCamelCase = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) 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''' lowercase__ : Optional[int]= 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 lowercase__ : Optional[int]= self.image_processor( snake_case__ , return_tensors=snake_case__ , do_normalize=snake_case__ , do_center_crop=snake_case__ , **snake_case__ ) encoding.update(snake_case__ ) return encoding def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.tokenizer.model_input_names lowercase__ : List[Any]= self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
721
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "AutoImageProcessor" __lowerCamelCase = "AutoTokenizer" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) lowercase__ : List[Any]= self.image_processor def __call__( self , snake_case__=None , snake_case__=None , snake_case__=None , **snake_case__ ): '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: lowercase__ : Tuple= self.tokenizer(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if images is not None: lowercase__ : str= self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if text is not None and images is not None: lowercase__ : Any= image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case__ ) , tensor_type=snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
85
0
"""simple docstring""" from ...processing_utils import ProcessorMixin class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "feature_extractor"] __lowerCamelCase = "TvltImageProcessor" __lowerCamelCase = "TvltFeatureExtractor" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(image_processor=snake_case__ , feature_extractor=snake_case__ ) lowercase__ : Union[str, Any]= image_processor lowercase__ : int= feature_extractor def __call__( self , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=False , snake_case__=False , *snake_case__ , **snake_case__ , ): '''simple docstring''' if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) lowercase__ : Union[str, Any]= None if images is not None: lowercase__ : Tuple= self.image_processor(snake_case__ , mask_pixel=snake_case__ , *snake_case__ , **snake_case__ ) if images_mixed is not None: lowercase__ : str= self.image_processor(snake_case__ , is_mixed=snake_case__ , *snake_case__ , **snake_case__ ) if audio is not None: lowercase__ : Tuple= self.feature_extractor( snake_case__ , *snake_case__ , sampling_rate=snake_case__ , mask_audio=snake_case__ , **snake_case__ ) lowercase__ : Tuple= {} if audio is not None: output_dict.update(snake_case__ ) if images is not None: output_dict.update(snake_case__ ) if images_mixed_dict is not None: output_dict.update(snake_case__ ) return output_dict @property def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.image_processor.model_input_names lowercase__ : Any= self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
700
"""simple docstring""" a : List[Any] = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/""" def lowercase__(A ) ->bytes: """simple docstring""" if not isinstance(A , A ): lowercase__ : Union[str, Any]= f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(A ) lowercase__ : str= "".join(bin(A )[2:].zfill(8 ) for byte in data ) lowercase__ : Tuple= len(A ) % 6 != 0 if padding_needed: # The padding that will be added later lowercase__ : Union[str, Any]= b"=" * ((6 - len(A ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(A ) % 6) else: lowercase__ : str= b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(A ) , 6 ) ).encode() + padding ) def lowercase__(A ) ->bytes: """simple docstring""" if not isinstance(A , A ) and not isinstance(A , A ): lowercase__ : str= ( "argument should be a bytes-like object or ASCII string, " f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(A ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(A , A ): try: lowercase__ : Optional[Any]= encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) lowercase__ : List[Any]= encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(A ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowercase__ : str= encoded_data[:-padding] lowercase__ : Tuple= "".join( bin(B64_CHARSET.index(A ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowercase__ : Tuple= "".join( bin(B64_CHARSET.index(A ) )[2:].zfill(6 ) for char in encoded_data ) lowercase__ : Any= [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(A ) , 8 ) ] return bytes(A ) if __name__ == "__main__": import doctest doctest.testmod()
85
0
"""simple docstring""" def lowercase__(A ) ->int: """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def lowercase__(A ) ->bool: """simple docstring""" lowercase__ : Optional[int]= 0 lowercase__ : Tuple= number while duplicate > 0: lowercase__ : Union[str, Any]= divmod(A , 10 ) fact_sum += factorial(A ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") a : Any = int(input("""Enter number: """).strip()) print( F"""{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.""" )
701
"""simple docstring""" from __future__ import annotations def lowercase__(A ) ->list[int]: # This function is recursive """simple docstring""" lowercase__ : int= len(A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else lowercase__ : str= array[0] lowercase__ : Optional[Any]= False lowercase__ : Any= 1 lowercase__ : list[int]= [] while not is_found and i < array_length: if array[i] < pivot: lowercase__ : Union[str, Any]= True lowercase__ : List[str]= [element for element in array[i:] if element >= array[i]] lowercase__ : Union[str, Any]= longest_subsequence(A ) if len(A ) > len(A ): lowercase__ : List[str]= temp_array else: i += 1 lowercase__ : List[str]= [element for element in array[1:] if element >= pivot] lowercase__ : List[str]= [pivot, *longest_subsequence(A )] if len(A ) > len(A ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
85
0
"""simple docstring""" from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def lowercase__() ->Optional[Any]: """simple docstring""" lowercase__ : List[Any]= ArgumentParser("Transformers CLI tool" , usage="transformers-cli <command> [<args>]" ) lowercase__ : Any= parser.add_subparsers(help="transformers-cli command helpers" ) # Register commands ConvertCommand.register_subcommand(A ) DownloadCommand.register_subcommand(A ) EnvironmentCommand.register_subcommand(A ) RunCommand.register_subcommand(A ) ServeCommand.register_subcommand(A ) UserCommands.register_subcommand(A ) AddNewModelCommand.register_subcommand(A ) AddNewModelLikeCommand.register_subcommand(A ) LfsCommands.register_subcommand(A ) PTtoTFCommand.register_subcommand(A ) # Let's go lowercase__ : Union[str, Any]= parser.parse_args() if not hasattr(A , "func" ): parser.print_help() exit(1 ) # Run lowercase__ : Dict= args.func(A ) service.run() if __name__ == "__main__": main()
702
"""simple docstring""" import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": a : int = argparse.ArgumentParser() parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--txt2img_unclip""", default="""kakaobrain/karlo-v1-alpha""", type=str, required=False, help="""The pretrained txt2img unclip.""", ) a : List[str] = parser.parse_args() a : List[str] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) a : Optional[Any] = CLIPImageProcessor() a : List[str] = CLIPVisionModelWithProjection.from_pretrained("""openai/clip-vit-large-patch14""") a : Tuple = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
0
"""simple docstring""" import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a : Optional[List[str]] = None a : Dict = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a : Optional[Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class __UpperCAmelCase: """simple docstring""" __lowerCamelCase = True __lowerCamelCase = None # Automatically constructed __lowerCamelCase = "PIL.Image.Image" __lowerCamelCase = pa.struct({"bytes": pa.binary(), "path": pa.string()} ) __lowerCamelCase = field(default="Image" , init=SCREAMING_SNAKE_CASE__ , repr=SCREAMING_SNAKE_CASE__ ) def __call__( self ): '''simple docstring''' return self.pa_type def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(snake_case__ , snake_case__ ): lowercase__ : Optional[Any]= np.array(snake_case__ ) if isinstance(snake_case__ , snake_case__ ): return {"path": value, "bytes": None} elif isinstance(snake_case__ , snake_case__ ): return {"path": None, "bytes": value} elif isinstance(snake_case__ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(snake_case__ ) elif isinstance(snake_case__ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(snake_case__ ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( F'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__=None ): '''simple docstring''' if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: lowercase__ : List[Any]= {} lowercase__ : str= value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(F'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(snake_case__ ): lowercase__ : int= PIL.Image.open(snake_case__ ) else: lowercase__ : List[str]= path.split("::" )[-1] try: lowercase__ : List[Any]= string_to_dict(snake_case__ , config.HUB_DATASETS_URL )["repo_id"] lowercase__ : Tuple= token_per_repo_id.get(snake_case__ ) except ValueError: lowercase__ : List[Any]= None with xopen(snake_case__ , "rb" , use_auth_token=snake_case__ ) as f: lowercase__ : Optional[Any]= BytesIO(f.read() ) lowercase__ : Dict= PIL.Image.open(bytes_ ) else: lowercase__ : Any= PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def UpperCAmelCase_ ( self ): '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if pa.types.is_string(storage.type ): lowercase__ : Optional[int]= pa.array([None] * len(snake_case__ ) , type=pa.binary() ) lowercase__ : Optional[int]= pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): lowercase__ : Optional[Any]= pa.array([None] * len(snake_case__ ) , type=pa.string() ) lowercase__ : List[str]= pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: lowercase__ : Union[str, Any]= storage.field("bytes" ) else: lowercase__ : Union[str, Any]= pa.array([None] * len(snake_case__ ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: lowercase__ : str= storage.field("path" ) else: lowercase__ : int= pa.array([None] * len(snake_case__ ) , type=pa.string() ) lowercase__ : List[Any]= pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): lowercase__ : Optional[int]= pa.array( [encode_np_array(np.array(snake_case__ ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) lowercase__ : List[Any]= pa.array([None] * len(snake_case__ ) , type=pa.string() ) lowercase__ : List[Any]= pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(snake_case__ , self.pa_type ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(snake_case__ ): with xopen(snake_case__ , "rb" ) as f: lowercase__ : Optional[int]= f.read() return bytes_ lowercase__ : List[str]= pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) lowercase__ : Optional[int]= pa.array( [os.path.basename(snake_case__ ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) lowercase__ : str= pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(snake_case__ , self.pa_type ) def lowercase__() ->List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() lowercase__ : Any= list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowercase__(A ) ->bytes: """simple docstring""" lowercase__ : Union[str, Any]= BytesIO() if image.format in list_image_compression_formats(): lowercase__ : Dict= image.format else: lowercase__ : List[str]= "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(A , format=A ) return buffer.getvalue() def lowercase__(A ) ->dict: """simple docstring""" if hasattr(A , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(A )} def lowercase__(A ) ->dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) lowercase__ : List[str]= array.dtype lowercase__ : Optional[int]= dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER lowercase__ : Optional[int]= dtype.kind lowercase__ : List[str]= dtype.itemsize lowercase__ : str= None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: lowercase__ : Optional[Any]= np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: lowercase__ : Any= dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: lowercase__ : List[Any]= dtype_byteorder + dtype_kind + str(A ) lowercase__ : Dict= np.dtype(A ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) lowercase__ : Tuple= PIL.Image.fromarray(array.astype(A ) ) return {"path": None, "bytes": image_to_bytes(A )} def lowercase__(A ) ->List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: lowercase__ : Any= first_non_null_value(A ) if isinstance(A , A ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(A , np.ndarray ): lowercase__ : Optional[Any]= no_op_if_value_is_null(A ) return [obj_to_image_dict_func(A ) for obj in objs] elif isinstance(A , PIL.Image.Image ): lowercase__ : List[str]= no_op_if_value_is_null(A ) return [obj_to_image_dict_func(A ) for obj in objs] else: return objs else: return objs
703
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() a : Optional[Any] = { """bart""": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), """bert""": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-base-cased-finetuned-mrpc""": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """dpr""": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), """gpt2""": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlnet""": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm""": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm-roberta""": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """transfo-xl""": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """openai-gpt""": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """roberta""": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """layoutlm""": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), """roberta-large-mnli""": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """camembert""": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """flaubert""": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert""": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert-base-distilled-squad""": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert""": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert-visual-feature-encoder""": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """ctrl""": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """albert""": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """t5""": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """electra""": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """wav2vec2""": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowercase__(A , A , A , A , A=False , A=True ) ->Union[str, Any]: """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase__, lowercase__, lowercase__, lowercase__ : List[Any]= MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: lowercase__ : List[str]= cached_file(A , A , force_download=not use_cached_models ) lowercase__ : List[Any]= config_class.from_json_file(A ) lowercase__ : Any= True lowercase__ : List[str]= True print(f'''Building TensorFlow model from configuration: {config}''' ) lowercase__ : Optional[int]= model_class(A ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): lowercase__ : List[str]= cached_file( A , A , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: lowercase__ : Union[str, Any]= load_pytorch_checkpoint_in_tfa_model(A , A ) if compare_with_pt_model: lowercase__ : Any= tf_model(tf_model.dummy_inputs , training=A ) # build the network lowercase__ : Optional[Any]= torch.load(A , map_location="cpu" ) lowercase__ : Union[str, Any]= pt_model_class.from_pretrained( pretrained_model_name_or_path=A , config=A , state_dict=A ) with torch.no_grad(): lowercase__ : str= pt_model(**pt_model.dummy_inputs ) lowercase__ : Tuple= pto[0].numpy() lowercase__ : List[Any]= tfo[0].numpy() lowercase__ : Any= np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2e-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(A , save_format="h5" ) def lowercase__(A , A , A=None , A=None , A=False , A=False , A=False , A=False , ) ->List[Any]: """simple docstring""" if args_model_type is None: lowercase__ : Tuple= list(MODEL_CLASSES.keys() ) else: lowercase__ : Optional[int]= [args_model_type] for j, model_type in enumerate(A , start=1 ): print("=" * 100 ) print(f''' Converting model type {j}/{len(A )}: {model_type}''' ) print("=" * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase__, lowercase__, lowercase__, lowercase__, lowercase__ : Optional[int]= MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: lowercase__ : int= list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: lowercase__ : Any= model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(A , A ) , start=1 ): print("-" * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue lowercase__ : Any= model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(A )}: {model_shortcut_name} - model_type {model_type}''' ) print("-" * 100 ) if config_shortcut_name in aws_config_map: lowercase__ : List[str]= cached_file(A , A , force_download=not use_cached_models ) else: lowercase__ : Union[str, Any]= config_shortcut_name if model_shortcut_name in aws_model_maps: lowercase__ : str= cached_file(A , A , force_download=not use_cached_models ) else: lowercase__ : Any= model_shortcut_name if os.path.isfile(A ): lowercase__ : Dict= "converted_model" convert_pt_checkpoint_to_tf( model_type=A , pytorch_checkpoint_path=A , config_file=A , tf_dump_path=os.path.join(A , model_shortcut_name + "-tf_model.h5" ) , compare_with_pt_model=A , ) if remove_cached_files: os.remove(A ) os.remove(A ) if __name__ == "__main__": a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file.""" ) parser.add_argument( """--model_type""", default=None, type=str, help=( F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ """convert all the models from AWS.""" ), ) parser.add_argument( """--pytorch_checkpoint_path""", default=None, type=str, help=( """Path to the PyTorch checkpoint path or shortcut name to download from AWS. """ """If not given, will download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--config_file""", default=None, type=str, help=( """The config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture. If not given and """ """--pytorch_checkpoint_path is not given or is a shortcut name """ """use the configuration associated to the shortcut name on the AWS""" ), ) parser.add_argument( """--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions.""" ) parser.add_argument( """--use_cached_models""", action="""store_true""", help="""Use cached models if possible instead of updating to latest checkpoint versions.""", ) parser.add_argument( """--remove_cached_files""", action="""store_true""", help="""Remove pytorch models after conversion (save memory when converting in batches).""", ) parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""") a : List[str] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
85
0
"""simple docstring""" from __future__ import annotations a : List[str] = list[list[int]] # assigning initial values to the grid a : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution a : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowercase__(A , A , A , A ) ->bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowercase__(A ) ->tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowercase__(A ) ->Matrix | None: """simple docstring""" if location := find_empty_location(A ): lowercase__ : str= location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(A , A , A , A ): lowercase__ : Any= digit if sudoku(A ) is not None: return grid lowercase__ : Optional[Any]= 0 return None def lowercase__(A ) ->None: """simple docstring""" for row in grid: for cell in row: print(A , end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") a : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
704
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule a : List[str] = {"""processing_wav2vec2_with_lm""": ["""Wav2Vec2ProcessorWithLM"""]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys a : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
85
0
def lowercase__(A , A ) ->int: """simple docstring""" while b: lowercase__ : List[str]= b, a % b return a def lowercase__(A , A ) ->int: """simple docstring""" return a if b == 0 else euclidean_gcd_recursive(A , a % b ) def lowercase__() ->List[str]: """simple docstring""" print(f'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(f'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(f'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(f'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(f'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(f'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(f'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(f'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
705
"""simple docstring""" def lowercase__(A ) ->list: """simple docstring""" if n_term == "": return [] lowercase__ : list= [] for temp in range(int(A ) ): series.append(f'''1/{temp + 1}''' if series else "1" ) return series if __name__ == "__main__": a : Dict = input("""Enter the last number (nth term) of the Harmonic Series""") print("""Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n""") print(harmonic_series(nth_term))
85
0
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand a : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def lowercase__(A ) ->Any: """simple docstring""" if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(A ): 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 lowercase__(A ) ->Tuple: """simple docstring""" lowercase__ : List[str]= pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) lowercase__ : Union[str, Any]= try_infer_format_from_ext(args.input ) if args.format == "infer" else args.format lowercase__ : Tuple= PipelineDataFormat.from_str( format=A , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(A , A ) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Any= nlp lowercase__ : Union[str, Any]= reader @staticmethod def UpperCAmelCase_ ( snake_case__ ): '''simple docstring''' lowercase__ : Union[str, Any]= 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=snake_case__ , help="Path to the file to use for inference" ) run_parser.add_argument("--output" , type=snake_case__ , help="Path to the file that will be used post to write results." ) run_parser.add_argument("--model" , type=snake_case__ , help="Name or path to the model to instantiate." ) run_parser.add_argument("--config" , type=snake_case__ , help="Name or path to the model's config to instantiate." ) run_parser.add_argument( "--tokenizer" , type=snake_case__ , help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column" , type=snake_case__ , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , ) run_parser.add_argument( "--format" , type=snake_case__ , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , ) run_parser.add_argument( "--device" , type=snake_case__ , 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=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self._nlp, [] for entry in self._reader: lowercase__ : Optional[Any]= nlp(**snake_case__ ) if self._reader.is_multi_columns else nlp(snake_case__ ) if isinstance(snake_case__ , snake_case__ ): outputs.append(snake_case__ ) else: outputs += output # Saving data if self._nlp.binary_output: lowercase__ : str= self._reader.save_binary(snake_case__ ) logger.warning(F'''Current pipeline requires output to be in binary format, saving at {binary_path}''' ) else: self._reader.save(snake_case__ )
706
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a : int = logging.get_logger(__name__) a : str = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "big_bird" def __init__( self , snake_case__=50358 , snake_case__=768 , snake_case__=12 , snake_case__=12 , snake_case__=3072 , snake_case__="gelu_new" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=4096 , snake_case__=2 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=True , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=66 , snake_case__="block_sparse" , snake_case__=True , snake_case__=False , snake_case__=64 , snake_case__=3 , snake_case__=None , **snake_case__ , ): '''simple docstring''' super().__init__( pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , sep_token_id=snake_case__ , **snake_case__ , ) lowercase__ : Dict= vocab_size lowercase__ : Optional[int]= max_position_embeddings lowercase__ : List[Any]= hidden_size lowercase__ : List[str]= num_hidden_layers lowercase__ : List[str]= num_attention_heads lowercase__ : Optional[int]= intermediate_size lowercase__ : Optional[int]= hidden_act lowercase__ : Tuple= hidden_dropout_prob lowercase__ : int= attention_probs_dropout_prob lowercase__ : int= initializer_range lowercase__ : List[Any]= type_vocab_size lowercase__ : Union[str, Any]= layer_norm_eps lowercase__ : Optional[Any]= use_cache lowercase__ : Union[str, Any]= rescale_embeddings lowercase__ : Union[str, Any]= attention_type lowercase__ : Any= use_bias lowercase__ : List[Any]= block_size lowercase__ : Optional[Any]= num_random_blocks lowercase__ : Optional[int]= classifier_dropout class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): '''simple docstring''' if self.task == "multiple-choice": lowercase__ : List[Any]= {0: "batch", 1: "choice", 2: "sequence"} else: lowercase__ : Tuple= {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
85
0
"""simple docstring""" import math def lowercase__(A , A ) ->float: """simple docstring""" if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative" ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(A ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="""malus_law""")
707
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
85
0
import math from collections.abc import Callable def lowercase__(A , A , A ) ->float: """simple docstring""" lowercase__ : float= xa lowercase__ : float= xa while True: if x_n == x_na or function(A ) == function(A ): raise ZeroDivisionError("float division by zero, could not find root" ) lowercase__ : float= x_na - ( function(A ) / ((function(A ) - function(A )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na lowercase__ : int= x_na lowercase__ : Union[str, Any]= x_na def lowercase__(A ) ->float: """simple docstring""" return math.pow(A , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
708
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def lowercase__(A , A ) ->List[Any]: """simple docstring""" lowercase__ : str= [] for part_id in partition_order: lowercase__ : int= df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(A ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->str: """simple docstring""" lowercase__ : Optional[Any]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Tuple= spark.range(100 ).repartition(1 ) lowercase__ : Dict= Spark(A ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Tuple: """simple docstring""" lowercase__ : Union[str, Any]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Dict= spark.range(10 ).repartition(2 ) lowercase__ : Optional[Any]= [1, 0] lowercase__ : List[str]= _generate_iterable_examples(A , A ) # Reverse the partitions. lowercase__ : int= _get_expected_row_ids_and_row_dicts_for_partition_order(A , A ) for i, (row_id, row_dict) in enumerate(generate_fn() ): lowercase__, lowercase__ : Any= expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->int: """simple docstring""" lowercase__ : int= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Dict= spark.range(10 ).repartition(1 ) lowercase__ : str= SparkExamplesIterable(A ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(A ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->str: """simple docstring""" lowercase__ : List[str]= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : int= spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("numpy.random.Generator" ) as generator_mock: lowercase__ : Optional[Any]= lambda A : x.reverse() lowercase__ : Tuple= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [2, 1, 0] ) lowercase__ : List[str]= SparkExamplesIterable(A ).shuffle_data_sources(A ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : str= expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Any: """simple docstring""" lowercase__ : Dict= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Union[str, Any]= spark.range(20 ).repartition(4 ) # Partitions 0 and 2 lowercase__ : Optional[int]= SparkExamplesIterable(A ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 lowercase__ : Union[str, Any]= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [0, 2] ) for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : Tuple= expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 lowercase__ : Tuple= SparkExamplesIterable(A ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 lowercase__ : List[Any]= _get_expected_row_ids_and_row_dicts_for_partition_order(A , [1, 3] ) for i, (row_id, row_dict) in enumerate(A ): lowercase__, lowercase__ : Dict= expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def lowercase__() ->Tuple: """simple docstring""" lowercase__ : Any= pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() lowercase__ : Tuple= spark.range(100 ).repartition(1 ) lowercase__ : Optional[int]= Spark(A ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
85
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging a : List[str] = logging.get_logger(__name__) a : Any = { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json""", } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "mvp" __lowerCamelCase = ["past_key_values"] __lowerCamelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , snake_case__=50267 , snake_case__=1024 , snake_case__=12 , snake_case__=4096 , snake_case__=16 , snake_case__=12 , snake_case__=4096 , snake_case__=16 , snake_case__=0.0 , snake_case__=0.0 , snake_case__="gelu" , snake_case__=1024 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.02 , snake_case__=0.0 , snake_case__=False , snake_case__=True , snake_case__=1 , snake_case__=0 , snake_case__=2 , snake_case__=True , snake_case__=2 , snake_case__=2 , snake_case__=False , snake_case__=100 , snake_case__=800 , **snake_case__ , ): '''simple docstring''' lowercase__ : Union[str, Any]= vocab_size lowercase__ : List[str]= max_position_embeddings lowercase__ : Dict= d_model lowercase__ : List[str]= encoder_ffn_dim lowercase__ : Dict= encoder_layers lowercase__ : Union[str, Any]= encoder_attention_heads lowercase__ : Any= decoder_ffn_dim lowercase__ : Union[str, Any]= decoder_layers lowercase__ : Union[str, Any]= decoder_attention_heads lowercase__ : Dict= dropout lowercase__ : Tuple= attention_dropout lowercase__ : int= activation_dropout lowercase__ : str= activation_function lowercase__ : str= init_std lowercase__ : Any= encoder_layerdrop lowercase__ : int= decoder_layerdrop lowercase__ : Union[str, Any]= classifier_dropout lowercase__ : Optional[int]= use_cache lowercase__ : List[str]= encoder_layers lowercase__ : List[str]= scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ : str= use_prompt lowercase__ : Optional[int]= prompt_length lowercase__ : Optional[int]= prompt_mid_dim 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__ , forced_eos_token_id=snake_case__ , **snake_case__ , ) if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , snake_case__ ): lowercase__ : Optional[int]= self.bos_token_id warnings.warn( F'''Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ''' "The config can simply be saved and uploaded again to be fixed." )
709
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=False , snake_case__=False , snake_case__=False , snake_case__=2 , snake_case__=99 , snake_case__=0 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=512 , snake_case__=12 , snake_case__=2 , snake_case__=0.02 , snake_case__=3 , snake_case__=4 , snake_case__="last" , snake_case__=None , snake_case__=None , ): '''simple docstring''' lowercase__ : Optional[int]= parent lowercase__ : Tuple= batch_size lowercase__ : Tuple= seq_length lowercase__ : str= is_training lowercase__ : str= use_input_lengths lowercase__ : Any= use_token_type_ids lowercase__ : List[Any]= use_labels lowercase__ : Optional[int]= gelu_activation lowercase__ : str= sinusoidal_embeddings lowercase__ : List[str]= causal lowercase__ : Any= asm lowercase__ : Optional[int]= n_langs lowercase__ : Union[str, Any]= vocab_size lowercase__ : int= n_special lowercase__ : Any= hidden_size lowercase__ : int= num_hidden_layers lowercase__ : List[str]= num_attention_heads lowercase__ : List[str]= hidden_dropout_prob lowercase__ : str= attention_probs_dropout_prob lowercase__ : Any= max_position_embeddings lowercase__ : List[Any]= type_vocab_size lowercase__ : int= type_sequence_label_size lowercase__ : Any= initializer_range lowercase__ : Optional[int]= num_labels lowercase__ : Union[str, Any]= num_choices lowercase__ : List[Any]= summary_type lowercase__ : Optional[int]= use_proj lowercase__ : int= scope def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : Dict= random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ : Tuple= None if self.use_input_lengths: lowercase__ : List[Any]= ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowercase__ : Tuple= None if self.use_token_type_ids: lowercase__ : Any= ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowercase__ : str= None lowercase__ : Tuple= None lowercase__ : Dict= None if self.use_labels: lowercase__ : Optional[Any]= ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Optional[Any]= ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase__ : Tuple= ids_tensor([self.batch_size] , 2 ).float() lowercase__ : Tuple= ids_tensor([self.batch_size] , self.num_choices ) lowercase__ : List[Any]= self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase_ ( self ): '''simple docstring''' return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : Any= FlaubertModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : str= model(snake_case__ , lengths=snake_case__ , langs=snake_case__ ) lowercase__ : str= model(snake_case__ , langs=snake_case__ ) lowercase__ : Any= model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : str= FlaubertWithLMHeadModel(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Optional[Any]= model(snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : str= FlaubertForQuestionAnsweringSimple(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : List[str]= model(snake_case__ ) lowercase__ : Dict= model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[Any]= FlaubertForQuestionAnswering(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= model(snake_case__ ) lowercase__ : Any= model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , p_mask=snake_case__ , ) lowercase__ : List[str]= model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , ) ((lowercase__), ) : Optional[Any]= result_with_labels.to_tuple() lowercase__ : Union[str, Any]= model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) ((lowercase__), ) : List[Any]= result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[str]= FlaubertForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Optional[Any]= model(snake_case__ ) lowercase__ : Optional[Any]= model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : List[Any]= self.num_labels lowercase__ : Union[str, Any]= FlaubertForTokenClassification(snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : int= model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ): '''simple docstring''' lowercase__ : int= self.num_choices lowercase__ : str= FlaubertForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowercase__ : Dict= input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : int= token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : str= input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ : Any= model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.prepare_config_and_inputs() ( ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ) : Any= config_and_inputs lowercase__ : Tuple= { "input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths, "attention_mask": input_mask, } return config, inputs_dict @require_torch class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) __lowerCamelCase = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__=False ): '''simple docstring''' lowercase__ : Tuple= super()._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": lowercase__ : List[Any]= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) lowercase__ : List[str]= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) return inputs_dict def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= FlaubertModelTester(self ) lowercase__ : List[str]= ConfigTester(self , config_class=snake_case__ , emb_dim=37 ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : List[str]= FlaubertModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__, lowercase__ : Optional[Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return lowercase__ : int= True lowercase__ : List[Any]= model_class(config=snake_case__ ) lowercase__ : str= self._prepare_for_class(snake_case__ , snake_case__ ) lowercase__ : Dict= torch.jit.trace( snake_case__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(snake_case__ , os.path.join(snake_case__ , "traced_model.pt" ) ) lowercase__ : str= torch.jit.load(os.path.join(snake_case__ , "traced_model.pt" ) , map_location=snake_case__ ) loaded(inputs_dict["input_ids"].to(snake_case__ ) , inputs_dict["attention_mask"].to(snake_case__ ) ) @require_torch class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= FlaubertModel.from_pretrained("flaubert/flaubert_base_cased" ) lowercase__ : Tuple= torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): lowercase__ : Optional[int]= model(snake_case__ )[0] lowercase__ : Optional[int]= torch.Size((1, 11, 768) ) self.assertEqual(output.shape , snake_case__ ) lowercase__ : Dict= torch.tensor( [[[-2.62_51, -1.42_98, -0.02_27], [-2.85_10, -1.63_87, 0.22_58], [-2.81_14, -1.18_32, -0.30_66]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) )
85
0
"""simple docstring""" from __future__ import annotations from fractions import Fraction def lowercase__(A , A ): """simple docstring""" return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def lowercase__(A ): """simple docstring""" lowercase__ : Tuple= [] lowercase__ : Dict= 11 lowercase__ : str= int("1" + "0" * digit_len ) for num in range(A , A ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(A , A ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 lowercase__ : str= 10 return solutions def lowercase__(A = 2 ): """simple docstring""" lowercase__ : Dict= 1.0 for fraction in fraction_list(A ): lowercase__ : Any= Fraction(A ) result *= frac.denominator / frac.numerator return int(A ) if __name__ == "__main__": print(solution())
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = None class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 2 @register_to_config def __init__( self , snake_case__ = 0.02 , snake_case__ = 100 , snake_case__ = 1.0_07 , snake_case__ = 80 , snake_case__ = 0.05 , snake_case__ = 50 , ): '''simple docstring''' # standard deviation of the initial noise distribution lowercase__ : int= sigma_max # setable values lowercase__ : int= None lowercase__ : np.IntTensor= None lowercase__ : torch.FloatTensor= None # sigma(t_i) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' return sample def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' lowercase__ : List[Any]= num_inference_steps lowercase__ : Any= np.arange(0 , self.num_inference_steps )[::-1].copy() lowercase__ : Tuple= torch.from_numpy(snake_case__ ).to(snake_case__ ) lowercase__ : Union[str, Any]= [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] lowercase__ : int= torch.tensor(snake_case__ , dtype=torch.floataa , device=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ = None ): '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: lowercase__ : Optional[Any]= min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: lowercase__ : str= 0 # sample eps ~ N(0, S_noise^2 * I) lowercase__ : List[Any]= self.config.s_noise * randn_tensor(sample.shape , generator=snake_case__ ).to(sample.device ) lowercase__ : str= sigma + gamma * sigma lowercase__ : Any= sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = True , ): '''simple docstring''' lowercase__ : Union[str, Any]= sample_hat + sigma_hat * model_output lowercase__ : Optional[int]= (sample_hat - pred_original_sample) / sigma_hat lowercase__ : Optional[Any]= sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=snake_case__ , derivative=snake_case__ , pred_original_sample=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = True , ): '''simple docstring''' lowercase__ : int= sample_prev + sigma_prev * model_output lowercase__ : Optional[int]= (sample_prev - pred_original_sample) / sigma_prev lowercase__ : Optional[Any]= sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=snake_case__ , derivative=snake_case__ , pred_original_sample=snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' raise NotImplementedError()
85
0
"""simple docstring""" from __future__ import annotations def lowercase__(A , A ) ->bool: """simple docstring""" lowercase__ : Union[str, Any]= get_failure_array(A ) # 2) Step through text searching for pattern lowercase__ : Union[str, Any]= 0, 0 # index into text, pattern while i < len(A ): if pattern[j] == text[i]: if j == (len(A ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: lowercase__ : str= failure[j - 1] continue i += 1 return False def lowercase__(A ) ->list[int]: """simple docstring""" lowercase__ : Tuple= [0] lowercase__ : List[str]= 0 lowercase__ : Optional[int]= 1 while j < len(A ): if pattern[i] == pattern[j]: i += 1 elif i > 0: lowercase__ : Dict= failure[i - 1] continue j += 1 failure.append(A ) return failure if __name__ == "__main__": # Test 1) a : Any = """abc1abc12""" a : int = """alskfjaldsabc1abc1abc12k23adsfabcabc""" a : Dict = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) a : str = """ABABX""" a : List[str] = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) a : Dict = """AAAB""" a : int = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) a : Optional[int] = """abcdabcy""" a : str = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) a : Tuple = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
711
"""simple docstring""" from ....utils import logging a : List[str] = logging.get_logger(__name__) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__=None , snake_case__=2048 ): '''simple docstring''' lowercase__ : Dict= config.__dict__ lowercase__ : str= modal_hidden_size if num_labels: lowercase__ : List[str]= num_labels
85
0
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() a : Optional[Any] = { """bart""": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), """bert""": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-base-cased-finetuned-mrpc""": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """dpr""": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), """gpt2""": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlnet""": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm""": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm-roberta""": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """transfo-xl""": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """openai-gpt""": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """roberta""": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """layoutlm""": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), """roberta-large-mnli""": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """camembert""": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """flaubert""": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert""": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert-base-distilled-squad""": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert""": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert-visual-feature-encoder""": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """ctrl""": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """albert""": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """t5""": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """electra""": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """wav2vec2""": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowercase__(A , A , A , A , A=False , A=True ) ->Union[str, Any]: """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase__ : List[Any]= MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: lowercase__ : List[str]= cached_file(A , A , force_download=not use_cached_models ) lowercase__ : List[Any]= config_class.from_json_file(A ) lowercase__ : Any= True lowercase__ : List[str]= True print(f'''Building TensorFlow model from configuration: {config}''' ) lowercase__ : Optional[int]= model_class(A ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): lowercase__ : List[str]= cached_file( A , A , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: lowercase__ : Union[str, Any]= load_pytorch_checkpoint_in_tfa_model(A , A ) if compare_with_pt_model: lowercase__ : Any= tf_model(tf_model.dummy_inputs , training=A ) # build the network lowercase__ : Optional[Any]= torch.load(A , map_location="cpu" ) lowercase__ : Union[str, Any]= pt_model_class.from_pretrained( pretrained_model_name_or_path=A , config=A , state_dict=A ) with torch.no_grad(): lowercase__ : str= pt_model(**pt_model.dummy_inputs ) lowercase__ : Tuple= pto[0].numpy() lowercase__ : List[Any]= tfo[0].numpy() lowercase__ : Any= np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2e-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(A , save_format="h5" ) def lowercase__(A , A , A=None , A=None , A=False , A=False , A=False , A=False , ) ->List[Any]: """simple docstring""" if args_model_type is None: lowercase__ : Tuple= list(MODEL_CLASSES.keys() ) else: lowercase__ : Optional[int]= [args_model_type] for j, model_type in enumerate(A , start=1 ): print("=" * 100 ) print(f''' Converting model type {j}/{len(A )}: {model_type}''' ) print("=" * 100 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase__ : Optional[int]= MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: lowercase__ : int= list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: lowercase__ : Any= model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(A , A ) , start=1 ): print("-" * 100 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue lowercase__ : Any= model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(A )}: {model_shortcut_name} - model_type {model_type}''' ) print("-" * 100 ) if config_shortcut_name in aws_config_map: lowercase__ : List[str]= cached_file(A , A , force_download=not use_cached_models ) else: lowercase__ : Union[str, Any]= config_shortcut_name if model_shortcut_name in aws_model_maps: lowercase__ : str= cached_file(A , A , force_download=not use_cached_models ) else: lowercase__ : Any= model_shortcut_name if os.path.isfile(A ): lowercase__ : Dict= "converted_model" convert_pt_checkpoint_to_tf( model_type=A , pytorch_checkpoint_path=A , config_file=A , tf_dump_path=os.path.join(A , model_shortcut_name + "-tf_model.h5" ) , compare_with_pt_model=A , ) if remove_cached_files: os.remove(A ) os.remove(A ) if __name__ == "__main__": a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file.""" ) parser.add_argument( """--model_type""", default=None, type=str, help=( F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ """convert all the models from AWS.""" ), ) parser.add_argument( """--pytorch_checkpoint_path""", default=None, type=str, help=( """Path to the PyTorch checkpoint path or shortcut name to download from AWS. """ """If not given, will download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--config_file""", default=None, type=str, help=( """The config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture. If not given and """ """--pytorch_checkpoint_path is not given or is a shortcut name """ """use the configuration associated to the shortcut name on the AWS""" ), ) parser.add_argument( """--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions.""" ) parser.add_argument( """--use_cached_models""", action="""store_true""", help="""Use cached models if possible instead of updating to latest checkpoint versions.""", ) parser.add_argument( """--remove_cached_files""", action="""store_true""", help="""Remove pytorch models after conversion (save memory when converting in batches).""", ) parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""") a : List[str] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
712
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def lowercase__(A ) ->int: """simple docstring""" lowercase__ : Optional[int]= [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def lowercase__(A , A ) ->Any: """simple docstring""" lowercase__ : Any= [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def lowercase__(A ) ->List[Any]: """simple docstring""" lowercase__ : Dict= [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', "stage2.cls_token") ) return token def lowercase__() ->Union[str, Any]: """simple docstring""" lowercase__ : Dict= [] head.append(("layernorm.weight", "norm.weight") ) head.append(("layernorm.bias", "norm.bias") ) head.append(("classifier.weight", "head.weight") ) head.append(("classifier.bias", "head.bias") ) return head def lowercase__(A , A , A , A ) ->Optional[int]: """simple docstring""" lowercase__ : List[str]= "imagenet-1k-id2label.json" lowercase__ : List[str]= 1_000 lowercase__ : Tuple= "huggingface/label-files" lowercase__ : int= num_labels lowercase__ : int= json.load(open(cached_download(hf_hub_url(A , A , repo_type="dataset" ) ) , "r" ) ) lowercase__ : str= {int(A ): v for k, v in idalabel.items()} lowercase__ : Optional[int]= idalabel lowercase__ : Union[str, Any]= {v: k for k, v in idalabel.items()} lowercase__ : Tuple= CvtConfig(num_labels=A , idalabel=A , labelaid=A ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13": lowercase__ : int= [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21": lowercase__ : Union[str, Any]= [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowercase__ : Optional[Any]= [2, 2, 20] lowercase__ : Optional[Any]= [3, 12, 16] lowercase__ : List[str]= [192, 768, 1_024] lowercase__ : List[str]= CvtForImageClassification(A ) lowercase__ : Any= AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" ) lowercase__ : Dict= image_size lowercase__ : int= torch.load(A , map_location=torch.device("cpu" ) ) lowercase__ : Optional[Any]= OrderedDict() lowercase__ : Tuple= [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowercase__ : Optional[int]= list_of_state_dict + cls_token(A ) lowercase__ : List[str]= list_of_state_dict + embeddings(A ) for cnt in range(config.depth[idx] ): lowercase__ : Dict= list_of_state_dict + attention(A , A ) lowercase__ : Optional[Any]= list_of_state_dict + final() for gg in list_of_state_dict: print(A ) for i in range(len(A ) ): lowercase__ : str= original_weights[list_of_state_dict[i][1]] model.load_state_dict(A ) model.save_pretrained(A ) image_processor.save_pretrained(A ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": a : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=384, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=r"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) a : Optional[int] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
85
0
"""simple docstring""" from string import ascii_lowercase, ascii_uppercase def lowercase__(A ) ->str: """simple docstring""" if not sentence: return "" lowercase__ : str= dict(zip(A , A ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
713
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = 42 def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__() self.register_modules(unet=snake_case__ , scheduler=snake_case__ ) @torch.no_grad() def __call__( self , snake_case__ = 1 , snake_case__ = 2000 , snake_case__ = None , snake_case__ = "pil" , snake_case__ = True , **snake_case__ , ): '''simple docstring''' lowercase__ : Optional[Any]= self.unet.config.sample_size lowercase__ : Dict= (batch_size, 3, img_size, img_size) lowercase__ : List[Any]= self.unet lowercase__ : Tuple= randn_tensor(snake_case__ , generator=snake_case__ ) * self.scheduler.init_noise_sigma lowercase__ : Tuple= sample.to(self.device ) self.scheduler.set_timesteps(snake_case__ ) self.scheduler.set_sigmas(snake_case__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowercase__ : Optional[Any]= self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): lowercase__ : List[Any]= self.unet(snake_case__ , snake_case__ ).sample lowercase__ : List[Any]= self.scheduler.step_correct(snake_case__ , snake_case__ , generator=snake_case__ ).prev_sample # prediction step lowercase__ : List[str]= model(snake_case__ , snake_case__ ).sample lowercase__ : Tuple= self.scheduler.step_pred(snake_case__ , snake_case__ , snake_case__ , generator=snake_case__ ) lowercase__, lowercase__ : Tuple= output.prev_sample, output.prev_sample_mean lowercase__ : List[str]= sample_mean.clamp(0 , 1 ) lowercase__ : Union[str, Any]= sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowercase__ : str= self.numpy_to_pil(snake_case__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=snake_case__ )
85
0
def lowercase__(A = 600_851_475_143 ) ->int: """simple docstring""" try: lowercase__ : List[Any]= int(A ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) lowercase__ : List[Any]= 2 lowercase__ : Dict= 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 lowercase__ : Union[str, Any]= i while n % i == 0: lowercase__ : Optional[int]= n // i i += 1 return int(A ) if __name__ == "__main__": print(F"""{solution() = }""")
714
"""simple docstring""" def lowercase__(A ) ->list[int]: """simple docstring""" lowercase__ : List[str]= len(A ) for i in range(A ): for j in range(i + 1 , A ): if numbers[j] < numbers[i]: lowercase__, lowercase__ : List[str]= numbers[j], numbers[i] return numbers if __name__ == "__main__": a : Dict = input("""Enter numbers separated by a comma:\n""").strip() a : List[str] = [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
85
0
"""simple docstring""" def lowercase__(A , A = False ) ->str: if not isinstance(A , A ): lowercase__ : Optional[int]= f'''Expected string as input, found {type(A )}''' raise ValueError(A ) if not isinstance(A , A ): lowercase__ : Union[str, Any]= f'''Expected boolean as use_pascal parameter, found {type(A )}''' raise ValueError(A ) lowercase__ : List[str]= input_str.split("_" ) lowercase__ : Optional[int]= 0 if use_pascal else 1 lowercase__ : List[str]= words[start_index:] lowercase__ : Any= [word[0].upper() + word[1:] for word in words_to_capitalize] lowercase__ : str= "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
715
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def lowercase__(A ) ->bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase__() ->Iterator[int]: """simple docstring""" lowercase__ : Union[str, Any]= 2 while True: if is_prime(A ): yield num num += 1 def lowercase__(A = 2_000_000 ) ->int: """simple docstring""" return sum(takewhile(lambda A : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"""{solution() = }""")
85
0
"""simple docstring""" import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowercase__(A , A , A ) ->str: """simple docstring""" if openai_config_file == "": lowercase__ : Any= OpenAIGPTConfig() else: lowercase__ : List[Any]= OpenAIGPTConfig.from_json_file(A ) lowercase__ : Optional[int]= OpenAIGPTModel(A ) # Load weights from numpy load_tf_weights_in_openai_gpt(A , A , A ) # Save pytorch-model lowercase__ : Union[str, Any]= pytorch_dump_folder_path + "/" + WEIGHTS_NAME lowercase__ : Any= pytorch_dump_folder_path + "/" + CONFIG_NAME print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() , A ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(A , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--openai_checkpoint_folder_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--openai_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) a : Union[str, Any] = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
716
"""simple docstring""" def lowercase__(A ) ->bool: """simple docstring""" lowercase__ : Tuple= (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowercase__(A = 5_000 ) ->int: """simple docstring""" lowercase__ : str= [(i * (3 * i - 1)) // 2 for i in range(1 , A )] for i, pentagonal_i in enumerate(A ): for j in range(A , len(A ) ): lowercase__ : List[Any]= pentagonal_nums[j] lowercase__ : int= pentagonal_i + pentagonal_j lowercase__ : Optional[int]= pentagonal_j - pentagonal_i if is_pentagonal(A ) and is_pentagonal(A ): return b return -1 if __name__ == "__main__": print(F"""{solution() = }""")
85
0
"""simple docstring""" def lowercase__(A = 100 ) ->int: """simple docstring""" lowercase__ : List[str]= set() lowercase__ : Optional[Any]= 0 lowercase__ : Any= n + 1 # maximum limit for a in range(2 , A ): for b in range(2 , A ): lowercase__ : Any= a**b # calculates the current power collect_powers.add(A ) # adds the result to the set return len(A ) if __name__ == "__main__": print("""Number of terms """, solution(int(str(input()).strip())))
717
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a : List[str] = logging.get_logger(__name__) a : Union[str, Any] = { """google/pix2struct-textcaps-base""": ( """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json""" ), } class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct_text_model" __lowerCamelCase = ["past_key_values"] __lowerCamelCase = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , snake_case__=50244 , snake_case__=768 , snake_case__=64 , snake_case__=2048 , snake_case__=12 , snake_case__=12 , snake_case__=32 , snake_case__=128 , snake_case__=0.1 , snake_case__=1e-6 , snake_case__=1.0 , snake_case__="gelu_new" , snake_case__=0 , snake_case__=False , snake_case__=0 , snake_case__=1 , snake_case__=False , snake_case__=True , **snake_case__ , ): '''simple docstring''' lowercase__ : int= vocab_size lowercase__ : Optional[Any]= hidden_size lowercase__ : Tuple= d_kv lowercase__ : Optional[int]= d_ff lowercase__ : Any= num_layers lowercase__ : Dict= num_heads lowercase__ : List[Any]= relative_attention_num_buckets lowercase__ : Optional[Any]= relative_attention_max_distance lowercase__ : Dict= dropout_rate lowercase__ : Tuple= layer_norm_epsilon lowercase__ : str= initializer_factor lowercase__ : Any= use_cache lowercase__ : Optional[int]= eos_token_id lowercase__ : str= decoder_start_token_id # for backwards compatibility lowercase__ : Optional[Any]= dense_act_fn super().__init__( pad_token_id=snake_case__ , eos_token_id=snake_case__ , decoder_start_token_id=snake_case__ , tie_word_embeddings=snake_case__ , is_decoder=snake_case__ , **snake_case__ , ) @classmethod def UpperCAmelCase_ ( cls , snake_case__ , **snake_case__ ): '''simple docstring''' cls._set_token_in_kwargs(snake_case__ ) lowercase__, lowercase__ : str= cls.get_config_dict(snake_case__ , **snake_case__ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("model_type" ) == "pix2struct": lowercase__ : str= config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(snake_case__ , **snake_case__ ) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct_vision_model" def __init__( self , snake_case__=768 , snake_case__=768 , snake_case__=2048 , snake_case__=64 , snake_case__=12 , snake_case__=12 , snake_case__="gelu_new" , snake_case__=1e-6 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=1e-10 , snake_case__=1.0 , snake_case__=4096 , snake_case__=32 , snake_case__=128 , **snake_case__ , ): '''simple docstring''' super().__init__(**snake_case__ ) lowercase__ : Tuple= hidden_size lowercase__ : Tuple= patch_embed_hidden_size lowercase__ : Optional[Any]= d_ff lowercase__ : Dict= dropout_rate lowercase__ : Any= num_hidden_layers lowercase__ : Optional[int]= num_attention_heads lowercase__ : Dict= initializer_range lowercase__ : Tuple= initializer_factor lowercase__ : Tuple= attention_dropout lowercase__ : Optional[Any]= layer_norm_eps lowercase__ : List[Any]= dense_act_fn lowercase__ : str= seq_len lowercase__ : List[str]= relative_attention_num_buckets lowercase__ : Union[str, Any]= relative_attention_max_distance lowercase__ : Dict= d_kv @classmethod def UpperCAmelCase_ ( cls , snake_case__ , **snake_case__ ): '''simple docstring''' cls._set_token_in_kwargs(snake_case__ ) lowercase__, lowercase__ : int= cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("model_type" ) == "pix2struct": lowercase__ : Union[str, Any]= 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(snake_case__ , **snake_case__ ) class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = "pix2struct" __lowerCamelCase = True def __init__( self , snake_case__=None , snake_case__=None , snake_case__=1.0 , snake_case__=0.02 , snake_case__=False , snake_case__=False , snake_case__=True , **snake_case__ , ): '''simple docstring''' super().__init__(tie_word_embeddings=snake_case__ , is_encoder_decoder=snake_case__ , **snake_case__ ) if text_config is None: lowercase__ : List[Any]= {} logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values." ) if vision_config is None: lowercase__ : str= {} logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values." ) lowercase__ : str= PixaStructTextConfig(**snake_case__ ) lowercase__ : Dict= PixaStructVisionConfig(**snake_case__ ) lowercase__ : int= self.text_config.decoder_start_token_id lowercase__ : List[Any]= self.text_config.pad_token_id lowercase__ : Any= self.text_config.eos_token_id lowercase__ : Any= initializer_factor lowercase__ : int= initializer_range lowercase__ : List[str]= self.initializer_range lowercase__ : List[str]= self.initializer_range lowercase__ : Dict= is_vqa @classmethod def UpperCAmelCase_ ( cls , snake_case__ , snake_case__ , **snake_case__ ): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= copy.deepcopy(self.__dict__ ) lowercase__ : str= self.text_config.to_dict() lowercase__ : str= self.vision_config.to_dict() lowercase__ : List[str]= self.__class__.model_type return output
85
0
"""simple docstring""" import random class __UpperCAmelCase: """simple docstring""" @staticmethod def UpperCAmelCase_ ( snake_case__ ): '''simple docstring''' lowercase__ : int= [ord(snake_case__ ) for i in text] lowercase__ : Optional[int]= [] lowercase__ : Tuple= [] for i in plain: lowercase__ : int= random.randint(1 , 300 ) lowercase__ : int= (i + k) * k cipher.append(snake_case__ ) key.append(snake_case__ ) return cipher, key @staticmethod def UpperCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : List[str]= [] for i in range(len(snake_case__ ) ): lowercase__ : Tuple= int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(snake_case__ ) ) return "".join(snake_case__ ) if __name__ == "__main__": a : Optional[Any] = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
718
"""simple docstring""" 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 tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) lowercase__ : str= AutoTokenizer.from_pretrained("google/mt5-small" ) lowercase__ : Tuple= tokenizer("Hello there" , return_tensors="tf" ).input_ids lowercase__ : Optional[Any]= tokenizer("Hi I am" , return_tensors="tf" ).input_ids lowercase__ : Optional[Any]= model(snake_case__ , labels=snake_case__ ).loss lowercase__ : int= -tf.math.reduce_mean(snake_case__ ).numpy() lowercase__ : int= -21.22_81_68 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
85
0
def lowercase__(A ) ->int: """simple docstring""" assert column_title.isupper() lowercase__ : List[Any]= 0 lowercase__ : Union[str, Any]= len(A ) - 1 lowercase__ : str= 0 while index >= 0: lowercase__ : Any= (ord(column_title[index] ) - 64) * pow(26 , A ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
719
"""simple docstring""" 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( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "BridgeTowerImageProcessor" __lowerCamelCase = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) 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''' lowercase__ : Optional[int]= 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 lowercase__ : Optional[int]= self.image_processor( snake_case__ , return_tensors=snake_case__ , do_normalize=snake_case__ , do_center_crop=snake_case__ , **snake_case__ ) encoding.update(snake_case__ ) return encoding def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.tokenizer.model_input_names lowercase__ : List[Any]= self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
0
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a : Tuple = """""" a : Optional[Any] = """""" a : Optional[int] = """""" a : int = 1 # (0 is vertical, 1 is horizontal) def lowercase__() ->None: """simple docstring""" lowercase__ : List[Any]= get_dataset(A , A ) print("Processing..." ) lowercase__ : List[str]= update_image_and_anno(A , A , A ) for index, image in enumerate(A ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase__ : Optional[Any]= random_chars(32 ) lowercase__ : str= paths[index].split(os.sep )[-1].rsplit("." , 1 )[0] lowercase__ : str= f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , A , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(A )} with {file_name}''' ) lowercase__ : Tuple= [] for anno in new_annos[index]: lowercase__ : str= f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(A ) with open(f'''/{file_root}.txt''' , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def lowercase__(A , A ) ->tuple[list, list]: """simple docstring""" lowercase__ : List[str]= [] lowercase__ : List[str]= [] for label_file in glob.glob(os.path.join(A , "*.txt" ) ): lowercase__ : Any= label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(A ) as in_file: lowercase__ : Any= in_file.readlines() lowercase__ : Any= os.path.join(A , f'''{label_name}.jpg''' ) lowercase__ : List[Any]= [] for obj_list in obj_lists: lowercase__ : Dict= obj_list.rstrip("\n" ).split(" " ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(A ) labels.append(A ) return img_paths, labels def lowercase__(A , A , A = 1 ) ->tuple[list, list, list]: """simple docstring""" lowercase__ : List[str]= [] lowercase__ : Any= [] lowercase__ : List[str]= [] for idx in range(len(A ) ): lowercase__ : str= [] lowercase__ : str= img_list[idx] path_list.append(A ) lowercase__ : Union[str, Any]= anno_list[idx] lowercase__ : str= cva.imread(A ) if flip_type == 1: lowercase__ : List[str]= cva.flip(A , A ) for bbox in img_annos: lowercase__ : List[str]= 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: lowercase__ : int= cva.flip(A , A ) for bbox in img_annos: lowercase__ : Tuple= 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(A ) new_imgs_list.append(A ) return new_imgs_list, new_annos_lists, path_list def lowercase__(A = 32 ) ->str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase__ : List[Any]= ascii_lowercase + digits return "".join(random.choice(A ) for _ in range(A ) ) if __name__ == "__main__": main() print("""DONE ✅""")
720
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= tempfile.mkdtemp() lowercase__ : Optional[Any]= 8 # DPR tok lowercase__ : Tuple= [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowercase__ : Any= os.path.join(self.tmpdirname , "dpr_tokenizer" ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) lowercase__ : Any= os.path.join(snake_case__ , DPR_VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) # BART tok lowercase__ : List[Any]= [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] lowercase__ : Tuple= dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) lowercase__ : Any= ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowercase__ : Tuple= {"unk_token": "<unk>"} lowercase__ : int= os.path.join(self.tmpdirname , "bart_tokenizer" ) os.makedirs(snake_case__ , exist_ok=snake_case__ ) lowercase__ : List[str]= os.path.join(snake_case__ , BART_VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : str= os.path.join(snake_case__ , BART_VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(snake_case__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(snake_case__ ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.get_dummy_dataset() lowercase__ : Optional[Any]= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: lowercase__ : Tuple= dataset lowercase__ : Optional[int]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : Dict= self.get_dummy_dataset() lowercase__ : Tuple= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="custom" , ) if from_disk: lowercase__ : Tuple= os.path.join(self.tmpdirname , "dataset" ) lowercase__ : Optional[Any]= os.path.join(self.tmpdirname , "index.faiss" ) dataset.get_index("embeddings" ).save(os.path.join(self.tmpdirname , "index.faiss" ) ) dataset.drop_index("embeddings" ) dataset.save_to_disk(os.path.join(self.tmpdirname , "dataset" ) ) del dataset lowercase__ : List[Any]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: lowercase__ : Optional[int]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , snake_case__ ) , ) return retriever def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) lowercase__ : Optional[int]= os.path.join(self.tmpdirname , "hf_bert_base.hnswSQ8_correct_phi_128.c_index" ) dataset.save_faiss_index("embeddings" , index_file_name + ".index.dpr" ) pickle.dump(dataset["id"] , open(index_file_name + ".index_meta.dpr" , "wb" ) ) lowercase__ : int= os.path.join(self.tmpdirname , "psgs_w100.tsv.pkl" ) lowercase__ : str= {sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(snake_case__ , open(snake_case__ , "wb" ) ) lowercase__ : List[Any]= RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="legacy" , index_path=self.tmpdirname , ) lowercase__ : Optional[Any]= RagRetriever( snake_case__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= 1 lowercase__ : Optional[Any]= self.get_dummy_canonical_hf_index_retriever() lowercase__ : Union[str, Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[int]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: lowercase__ : Tuple= self.get_dummy_dataset() retriever.save_pretrained(snake_case__ ) lowercase__ : int= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : Any= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Tuple= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= 1 lowercase__ : Any= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) lowercase__ : Union[str, Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Any= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : int= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : Tuple= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : str= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Any= 1 lowercase__ : str= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) lowercase__ : List[str]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[int]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : Optional[Any]= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : int= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Union[str, Any]= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= 1 lowercase__ : int= self.get_dummy_legacy_index_retriever() lowercase__ : Optional[Any]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__, lowercase__, lowercase__ : Optional[Any]= retriever.retrieve(snake_case__ , n_docs=snake_case__ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(snake_case__ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["text", "title"] ) self.assertEqual(len(doc_dicts[0]["text"] ) , snake_case__ ) self.assertEqual(doc_dicts[0]["text"][0] , "bar" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] , "foo" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(snake_case__ ) lowercase__ : List[Any]= RagRetriever.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) lowercase__ : str= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Tuple= retriever.retrieve(snake_case__ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self ): '''simple docstring''' import torch lowercase__ : str= 1 lowercase__ : Union[str, Any]= self.get_dummy_canonical_hf_index_retriever() lowercase__ : str= [[5, 7], [10, 11]] lowercase__ : List[str]= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : Dict= retriever(snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ ) lowercase__, lowercase__, lowercase__ : Optional[int]= ( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertIsInstance(snake_case__ , np.ndarray ) lowercase__ : Any= retriever( snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ , return_tensors="pt" , ) lowercase__, lowercase__, lowercase__, lowercase__ : Tuple= ( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(snake_case__ , torch.Tensor ) self.assertIsInstance(snake_case__ , torch.Tensor ) self.assertIsInstance(snake_case__ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.get_dpr_ctx_encoder_tokenizer() lowercase__ : Dict= 1 lowercase__ : Any= self.get_dummy_custom_hf_index_retriever(from_disk=snake_case__ ) retriever.set_ctx_encoder_tokenizer(snake_case__ ) lowercase__ : List[str]= [[5, 7], [10, 11]] lowercase__ : Any= np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) lowercase__ : List[Any]= retriever(snake_case__ , snake_case__ , prefix=retriever.config.generator.prefix , n_docs=snake_case__ ) self.assertEqual( len(snake_case__ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask") ) , snake_case__ ) # check for doc token related keys in dictionary.
85
0
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__ , snake_case__=3 , snake_case__=32 , snake_case__=3 , snake_case__=10 , snake_case__=[10, 20, 30, 40] , snake_case__=[1, 1, 2, 1] , snake_case__=True , snake_case__=True , snake_case__="relu" , snake_case__=3 , snake_case__=None , ): '''simple docstring''' lowercase__ : int= parent lowercase__ : Union[str, Any]= batch_size lowercase__ : int= image_size lowercase__ : Union[str, Any]= num_channels lowercase__ : int= embeddings_size lowercase__ : Optional[Any]= hidden_sizes lowercase__ : List[Any]= depths lowercase__ : Optional[int]= is_training lowercase__ : Tuple= use_labels lowercase__ : str= hidden_act lowercase__ : Tuple= num_labels lowercase__ : Union[str, Any]= scope lowercase__ : Optional[Any]= len(snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Dict= None if self.use_labels: lowercase__ : Tuple= ids_tensor([self.batch_size] , self.num_labels ) lowercase__ : str= self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : List[str]= TFRegNetModel(config=snake_case__ ) lowercase__ : Union[str, Any]= model(snake_case__ , training=snake_case__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : str= self.num_labels lowercase__ : str= TFRegNetForImageClassification(snake_case__ ) lowercase__ : List[str]= model(snake_case__ , labels=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= self.prepare_config_and_inputs() lowercase__ : List[Any]= config_and_inputs lowercase__ : Union[str, Any]= {"pixel_values": pixel_values} return config, inputs_dict @require_tf class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" __lowerCamelCase = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __lowerCamelCase = ( {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification} if is_tf_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= TFRegNetModelTester(self ) lowercase__ : List[Any]= ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' return @unittest.skip(reason="RegNet does not use inputs_embeds" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason="RegNet does not support input and output embeddings" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Tuple= model_class(snake_case__ ) lowercase__ : Union[str, Any]= inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Tuple= [*signature.parameters.keys()] lowercase__ : Tuple= ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' def check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ): lowercase__ : Optional[Any]= model_class(snake_case__ ) lowercase__ : str= model(**self._prepare_for_class(snake_case__ , snake_case__ ) , training=snake_case__ ) lowercase__ : Optional[int]= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase__ : Any= self.model_tester.num_stages self.assertEqual(len(snake_case__ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowercase__ : Any= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int= ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowercase__ : int= layer_type lowercase__ : List[Any]= True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : int= True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(snake_case__ , snake_case__ , snake_case__ , snake_case__={} ): lowercase__ : int= model(snake_case__ , return_dict=snake_case__ , **snake_case__ ) lowercase__ : List[str]= model(snake_case__ , return_dict=snake_case__ , **snake_case__ ).to_tuple() def recursive_check(snake_case__ , snake_case__ ): if isinstance(snake_case__ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(snake_case__ , snake_case__ ): recursive_check(snake_case__ , snake_case__ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(snake_case__ , snake_case__ ) ) , msg=( "Tuple and dict output are not equal. Difference:" F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(snake_case__ , snake_case__ ) for model_class in self.all_model_classes: lowercase__ : int= model_class(snake_case__ ) lowercase__ : str= self._prepare_for_class(snake_case__ , snake_case__ ) lowercase__ : List[Any]= self._prepare_for_class(snake_case__ , snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ ) lowercase__ : Optional[Any]= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) lowercase__ : Any= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ ) lowercase__ : Union[str, Any]= self._prepare_for_class(snake_case__ , snake_case__ ) lowercase__ : List[str]= self._prepare_for_class(snake_case__ , snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ , {"output_hidden_states": True} ) lowercase__ : int= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) lowercase__ : Dict= self._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) check_equivalence(snake_case__ , snake_case__ , snake_case__ , {"output_hidden_states": True} ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[str]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : Dict= TFRegNetModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def lowercase__() ->Union[str, Any]: """simple docstring""" lowercase__ : Union[str, Any]= Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowercase__ : List[str]= self.default_image_processor lowercase__ : Any= prepare_img() lowercase__ : List[str]= image_processor(images=snake_case__ , return_tensors="tf" ) # forward pass lowercase__ : Dict= model(**snake_case__ , training=snake_case__ ) # verify the logits lowercase__ : Tuple= tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , snake_case__ ) lowercase__ : str= tf.constant([-0.41_80, -1.50_51, -3.48_36] ) tf.debugging.assert_near(outputs.logits[0, :3] , snake_case__ , atol=1e-4 )
721
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_processor", "tokenizer"] __lowerCamelCase = "AutoImageProcessor" __lowerCamelCase = "AutoTokenizer" def __init__( self , snake_case__ , snake_case__ ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) lowercase__ : List[Any]= self.image_processor def __call__( self , snake_case__=None , snake_case__=None , snake_case__=None , **snake_case__ ): '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: lowercase__ : Tuple= self.tokenizer(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if images is not None: lowercase__ : str= self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if text is not None and images is not None: lowercase__ : Any= image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case__ ) , tensor_type=snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ): '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
85
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''uclanlp/visualbert-vqa''': '''https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json''', '''uclanlp/visualbert-vqa-pre''': '''https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json''', '''uclanlp/visualbert-vqa-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-vcr''': '''https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json''', '''uclanlp/visualbert-vcr-pre''': '''https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json''', '''uclanlp/visualbert-vcr-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-nlvr2''': '''https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-pre''': '''https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json''' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """visual_bert""" def __init__(self , SCREAMING_SNAKE_CASE_=3_05_22 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = hidden_size UpperCamelCase__ = visual_embedding_dim UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = type_vocab_size UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = bypass_transformer UpperCamelCase__ = special_visual_initialize
86
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
1
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } lowerCamelCase_ = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def __magic_name__ ( __a : int , __a : List[str] , __a : Optional[Any] , __a : int , __a : Tuple ): '''simple docstring''' for attribute in key.split(""".""" ): UpperCamelCase__ = getattr(__a , __a ) if weight_type is not None: UpperCamelCase__ = getattr(__a , __a ).shape else: UpperCamelCase__ = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": UpperCamelCase__ = value elif weight_type == "weight_g": UpperCamelCase__ = value elif weight_type == "weight_v": UpperCamelCase__ = value elif weight_type == "bias": UpperCamelCase__ = value else: UpperCamelCase__ = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __magic_name__ ( __a : Dict , __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = fairseq_model.state_dict() UpperCamelCase__ = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase__ = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase__ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase__ = True if "*" in mapped_key: UpperCamelCase__ = name.split(__a )[0].split(""".""" )[-2] UpperCamelCase__ = mapped_key.replace("""*""" , __a ) if "weight_g" in name: UpperCamelCase__ = """weight_g""" elif "weight_v" in name: UpperCamelCase__ = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase__ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase__ = """weight""" else: UpperCamelCase__ = None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f"Unused weights: {unused_weights}" ) def __magic_name__ ( __a : Any , __a : str , __a : Tuple , __a : Optional[Any] , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = full_name.split("""conv_layers.""" )[-1] UpperCamelCase__ = name.split(""".""" ) UpperCamelCase__ = int(items[0] ) UpperCamelCase__ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) UpperCamelCase__ = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) UpperCamelCase__ = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) UpperCamelCase__ = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) UpperCamelCase__ = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(__a ) @torch.no_grad() def __magic_name__ ( __a : List[Any] , __a : Any , __a : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase__ = torch.load(__a ) UpperCamelCase__ = WavLMConfigOrig(checkpoint["""cfg"""] ) UpperCamelCase__ = WavLMOrig(__a ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: UpperCamelCase__ = WavLMConfig.from_pretrained(__a ) else: UpperCamelCase__ = WavLMConfig() UpperCamelCase__ = WavLMModel(__a ) recursively_load_weights(__a , __a ) hf_wavlm.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') lowerCamelCase_ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size 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__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): 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] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
1
def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def __magic_name__ ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
86
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
1
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class __A( yaml.SafeLoader ): """simple docstring""" def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [self.constructed_objects[key_node] for key_node, _ in node.value] UpperCamelCase__ = [tuple(SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else key for key in keys] UpperCamelCase__ = Counter(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = super().construct_mapping(SCREAMING_SNAKE_CASE_ , deep=SCREAMING_SNAKE_CASE_ ) self._check_no_duplicates_on_constructed_node(SCREAMING_SNAKE_CASE_ ) return mapping def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: UpperCamelCase__ = full_content[1:].index("""---""" ) + 1 UpperCamelCase__ = """\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(__a ) class __A( __lowerCamelCase ): """simple docstring""" # class attributes SCREAMING_SNAKE_CASE__ = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def UpperCAmelCase_ (cls , SCREAMING_SNAKE_CASE_ ): with open(SCREAMING_SNAKE_CASE_ , encoding="""utf-8""" ) as readme_file: UpperCamelCase__ , UpperCamelCase__ = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(SCREAMING_SNAKE_CASE_ ) else: return cls() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): if path.exists(): with open(SCREAMING_SNAKE_CASE_ , encoding="""utf-8""" ) as readme_file: UpperCamelCase__ = readme_file.read() else: UpperCamelCase__ = None UpperCamelCase__ = self._to_readme(SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = None ): if readme_content is not None: UpperCamelCase__ , UpperCamelCase__ = _split_yaml_from_readme(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """---\n""" + self.to_yaml_string() + """---\n""" + content else: UpperCamelCase__ = """---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def UpperCAmelCase_ (cls , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = yaml.load(SCREAMING_SNAKE_CASE_ , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields UpperCamelCase__ = { (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=SCREAMING_SNAKE_CASE_ , allow_unicode=SCREAMING_SNAKE_CASE_ , encoding="""utf-8""" , ).decode("""utf-8""" ) lowerCamelCase_ = { '''image-classification''': [], '''translation''': [], '''image-segmentation''': [], '''fill-mask''': [], '''automatic-speech-recognition''': [], '''token-classification''': [], '''sentence-similarity''': [], '''audio-classification''': [], '''question-answering''': [], '''summarization''': [], '''zero-shot-classification''': [], '''table-to-text''': [], '''feature-extraction''': [], '''other''': [], '''multiple-choice''': [], '''text-classification''': [], '''text-to-image''': [], '''text2text-generation''': [], '''zero-shot-image-classification''': [], '''tabular-classification''': [], '''tabular-regression''': [], '''image-to-image''': [], '''tabular-to-text''': [], '''unconditional-image-generation''': [], '''text-retrieval''': [], '''text-to-speech''': [], '''object-detection''': [], '''audio-to-audio''': [], '''text-generation''': [], '''conversational''': [], '''table-question-answering''': [], '''visual-question-answering''': [], '''image-to-text''': [], '''reinforcement-learning''': [], '''voice-activity-detection''': [], '''time-series-forecasting''': [], '''document-question-answering''': [], } if __name__ == "__main__": from argparse import ArgumentParser lowerCamelCase_ = ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''') ap.add_argument('''readme_filepath''') lowerCamelCase_ = ap.parse_args() lowerCamelCase_ = Path(args.readme_filepath) lowerCamelCase_ = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
86
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
1
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
1
from typing import List from .keymap import KEYMAP, get_character def __magic_name__ ( __a : str ): '''simple docstring''' def decorator(__a : Tuple ): UpperCamelCase__ = getattr(__a , """handle_key""" , [] ) handle += [key] setattr(__a , """handle_key""" , __a ) return func return decorator def __magic_name__ ( *__a : List[str] ): '''simple docstring''' def decorator(__a : List[Any] ): UpperCamelCase__ = getattr(__a , """handle_key""" , [] ) handle += keys setattr(__a , """handle_key""" , __a ) return func return decorator class __A( __lowerCamelCase ): """simple docstring""" def __new__(cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = super().__new__(cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not hasattr(SCREAMING_SNAKE_CASE_ , """key_handler""" ): setattr(SCREAMING_SNAKE_CASE_ , """key_handler""" , {} ) setattr(SCREAMING_SNAKE_CASE_ , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): UpperCamelCase__ = getattr(SCREAMING_SNAKE_CASE_ , """handle_key""" , [] ) for key in handled_keys: UpperCamelCase__ = value return new_cls @staticmethod def UpperCAmelCase_ (cls ): UpperCamelCase__ = get_character() if char != KEYMAP["undefined"]: UpperCamelCase__ = ord(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = cls.key_handler.get(SCREAMING_SNAKE_CASE_ ) if handler: UpperCamelCase__ = char return handler(cls ) else: return None def __magic_name__ ( cls : Union[str, Any] ): '''simple docstring''' return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] lowerCamelCase_ = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from collections import deque from .hash_table import HashTable class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.values[key] def UpperCAmelCase_ (self ): return ( sum(self.charge_factor - len(SCREAMING_SNAKE_CASE_ ) for slot in self.values ) / self.size_table * self.charge_factor ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(SCREAMING_SNAKE_CASE_ ) == 0 ): return key return super()._collision_resolution(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @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 __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging lowerCamelCase_ = '''\ ''' lowerCamelCase_ = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' lowerCamelCase_ = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """input_texts""": datasets.Value("""string""" ), } ) , reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_=None ): if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": UpperCamelCase__ = """cuda""" else: UpperCamelCase__ = """cuda""" if torch.cuda.is_available() else """cpu""" UpperCamelCase__ = AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: UpperCamelCase__ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(SCREAMING_SNAKE_CASE_ ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" UpperCamelCase__ = model.config.max_length - 1 else: UpperCamelCase__ = model.config.max_length UpperCamelCase__ = tokenizer( SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encodings["""input_ids"""] UpperCamelCase__ = encodings["""attention_mask"""] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." UpperCamelCase__ = [] UpperCamelCase__ = CrossEntropyLoss(reduction="""none""" ) for start_index in logging.tqdm(range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase__ = min(start_index + batch_size , len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = encoded_texts[start_index:end_index] UpperCamelCase__ = attn_masks[start_index:end_index] if add_start_token: UpperCamelCase__ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) UpperCamelCase__ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(SCREAMING_SNAKE_CASE_ ), attn_mask] , dim=1 ) UpperCamelCase__ = encoded_batch with torch.no_grad(): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).logits UpperCamelCase__ = out_logits[..., :-1, :].contiguous() UpperCamelCase__ = labels[..., 1:].contiguous() UpperCamelCase__ = attn_mask[..., 1:].contiguous() UpperCamelCase__ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , SCREAMING_SNAKE_CASE_ ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(SCREAMING_SNAKE_CASE_ )}
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
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, ) lowerCamelCase_ = logging.getLogger(__name__) @dataclass(frozen=__lowerCamelCase ) class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None @dataclass(frozen=__lowerCamelCase ) class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if is_torch_available(): import torch from torch.utils.data import Dataset class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_ = False , ): UpperCamelCase__ = hans_processors[task]() UpperCamelCase__ = os.path.join( SCREAMING_SNAKE_CASE_ , """cached_{}_{}_{}_{}""".format( """dev""" if evaluate else """train""" , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , ) , ) UpperCamelCase__ = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) UpperCamelCase__ , UpperCamelCase__ = label_list[2], label_list[1] UpperCamelCase__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCamelCase__ = cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE_ ): if os.path.exists(SCREAMING_SNAKE_CASE_ ) and not overwrite_cache: logger.info(F"Loading features from cached file {cached_features_file}" ) UpperCamelCase__ = torch.load(SCREAMING_SNAKE_CASE_ ) else: logger.info(F"Creating features from dataset file at {data_dir}" ) UpperCamelCase__ = ( processor.get_dev_examples(SCREAMING_SNAKE_CASE_ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_ ) ) logger.info("""Training examples: %s""" , len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info("""Saving features into cached file %s""" , SCREAMING_SNAKE_CASE_ ) torch.save(self.features , SCREAMING_SNAKE_CASE_ ) def __len__(self ): return len(self.features ) def __getitem__(self , SCREAMING_SNAKE_CASE_ ): return self.features[i] def UpperCAmelCase_ (self ): return self.label_list if is_tf_available(): import tensorflow as tf class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_ = False , ): UpperCamelCase__ = hans_processors[task]() UpperCamelCase__ = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) UpperCamelCase__ , UpperCamelCase__ = label_list[2], label_list[1] UpperCamelCase__ = label_list UpperCamelCase__ = processor.get_dev_examples(SCREAMING_SNAKE_CASE_ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="""convert examples to features""" ): if ex_index % 1_00_00 == 0: logger.info("""Writing example %d of %d""" % (ex_index, len(SCREAMING_SNAKE_CASE_ )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) UpperCamelCase__ = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE_ , ( { """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 UpperCAmelCase_ (self ): return self.dataset def __len__(self ): return len(self.features ) def __getitem__(self , SCREAMING_SNAKE_CASE_ ): return self.features[i] def UpperCAmelCase_ (self ): return self.label_list class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_ , """heuristics_train_set.txt""" ) ) , """train""" ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_ , """heuristics_evaluation_set.txt""" ) ) , """dev""" ) def UpperCAmelCase_ (self ): return ["contradiction", "entailment", "neutral"] def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for i, line in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: continue UpperCamelCase__ = """%s-%s""" % (set_type, line[0]) UpperCamelCase__ = line[5] UpperCamelCase__ = line[6] UpperCamelCase__ = line[7][2:] if line[7].startswith("""ex""" ) else line[7] UpperCamelCase__ = line[0] examples.append(InputExample(guid=SCREAMING_SNAKE_CASE_ , text_a=SCREAMING_SNAKE_CASE_ , text_b=SCREAMING_SNAKE_CASE_ , label=SCREAMING_SNAKE_CASE_ , pairID=SCREAMING_SNAKE_CASE_ ) ) return examples def __magic_name__ ( __a : List[InputExample] , __a : List[str] , __a : int , __a : PreTrainedTokenizer , ): '''simple docstring''' UpperCamelCase__ = {label: i for i, label in enumerate(__a )} UpperCamelCase__ = [] for ex_index, example in tqdm.tqdm(enumerate(__a ) , desc="""convert examples to features""" ): if ex_index % 10_000 == 0: logger.info("""Writing example %d""" % (ex_index) ) UpperCamelCase__ = tokenizer( example.text_a , example.text_b , add_special_tokens=__a , max_length=__a , padding="""max_length""" , truncation=__a , return_overflowing_tokens=__a , ) UpperCamelCase__ = label_map[example.label] if example.label in label_map else 0 UpperCamelCase__ = int(example.pairID ) features.append(InputFeatures(**__a , label=__a , pairID=__a ) ) for i, example in enumerate(examples[:5] ): logger.info("""*** Example ***""" ) logger.info(f"guid: {example}" ) logger.info(f"features: {features[i]}" ) return features lowerCamelCase_ = { '''hans''': 3, } lowerCamelCase_ = { '''hans''': HansProcessor, }
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __a : dict , __a : str , __a : set , __a : set , __a : dict , __a : dict , __a : PriorityQueue , __a : dict , __a : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue UpperCamelCase__ = cst_fwd.get(__a , np.inf ) UpperCamelCase__ = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) UpperCamelCase__ = new_cost_f UpperCamelCase__ = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: UpperCamelCase__ = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __a : str , __a : str , __a : dict , __a : dict ): '''simple docstring''' UpperCamelCase__ = -1 UpperCamelCase__ = set() UpperCamelCase__ = set() UpperCamelCase__ = {source: 0} UpperCamelCase__ = {destination: 0} UpperCamelCase__ = {source: None} UpperCamelCase__ = {destination: None} UpperCamelCase__ = PriorityQueue() UpperCamelCase__ = PriorityQueue() UpperCamelCase__ = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): UpperCamelCase__ , UpperCamelCase__ = queue_forward.get() visited_forward.add(__a ) UpperCamelCase__ , UpperCamelCase__ = queue_backward.get() visited_backward.add(__a ) UpperCamelCase__ = pass_and_relaxation( __a , __a , __a , __a , __a , __a , __a , __a , __a , ) UpperCamelCase__ = pass_and_relaxation( __a , __a , __a , __a , __a , __a , __a , __a , __a , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: UpperCamelCase__ = shortest_distance return shortest_path_distance lowerCamelCase_ = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } lowerCamelCase_ = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class __A( __lowerCamelCase , __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """pixel_values""" SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = TimmBackboneConfig def __init__(self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , """timm""" ) super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = config if config.backbone is None: raise ValueError("""backbone is not set in the config. Please set it to a timm model name.""" ) if config.backbone not in timm.list_models(): raise ValueError(F"backbone {config.backbone} is not supported by timm." ) if hasattr(SCREAMING_SNAKE_CASE_ , """out_features""" ) and config.out_features is not None: raise ValueError("""out_features is not supported by TimmBackbone. Please use out_indices instead.""" ) UpperCamelCase__ = getattr(SCREAMING_SNAKE_CASE_ , """use_pretrained_backbone""" , SCREAMING_SNAKE_CASE_ ) if pretrained is None: raise ValueError("""use_pretrained_backbone is not set in the config. Please set it to True or False.""" ) # We just take the final layer by default. This matches the default for the transformers models. UpperCamelCase__ = config.out_indices if getattr(SCREAMING_SNAKE_CASE_ , """out_indices""" , SCREAMING_SNAKE_CASE_ ) is not None else (-1,) UpperCamelCase__ = timm.create_model( config.backbone , pretrained=SCREAMING_SNAKE_CASE_ , features_only=config.features_only , in_chans=config.num_channels , out_indices=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. UpperCamelCase__ = self._backbone.return_layers UpperCamelCase__ = {layer["""module"""]: str(SCREAMING_SNAKE_CASE_ ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase_ (cls , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""vision""", """timm"""] ) from ...models.timm_backbone import TimmBackboneConfig UpperCamelCase__ = kwargs.pop("""config""" , TimmBackboneConfig() ) UpperCamelCase__ = kwargs.pop("""use_timm_backbone""" , SCREAMING_SNAKE_CASE_ ) if not use_timm: raise ValueError("""use_timm_backbone must be True for timm backbones""" ) UpperCamelCase__ = kwargs.pop("""num_channels""" , config.num_channels ) UpperCamelCase__ = kwargs.pop("""features_only""" , config.features_only ) UpperCamelCase__ = kwargs.pop("""use_pretrained_backbone""" , config.use_pretrained_backbone ) UpperCamelCase__ = kwargs.pop("""out_indices""" , config.out_indices ) UpperCamelCase__ = TimmBackboneConfig( backbone=SCREAMING_SNAKE_CASE_ , num_channels=SCREAMING_SNAKE_CASE_ , features_only=SCREAMING_SNAKE_CASE_ , use_pretrained_backbone=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , ) return super()._from_config(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): pass def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase__ = output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError("""Cannot output attentions for timm backbones at the moment""" ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone UpperCamelCase__ = self._all_layers UpperCamelCase__ = self._backbone(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self._return_layers UpperCamelCase__ = tuple(hidden_states[i] for i in self.out_indices ) else: UpperCamelCase__ = self._backbone(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None UpperCamelCase__ = tuple(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tuple(SCREAMING_SNAKE_CASE_ ) if hidden_states is not None else None if not return_dict: UpperCamelCase__ = (feature_maps,) if output_hidden_states: UpperCamelCase__ = output + (hidden_states,) return output return BackboneOutput(feature_maps=SCREAMING_SNAKE_CASE_ , hidden_states=SCREAMING_SNAKE_CASE_ , attentions=SCREAMING_SNAKE_CASE_ )
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
from typing import Any import numpy as np def __magic_name__ ( __a : np.ndarray ): '''simple docstring''' return np.array_equal(__a , matrix.conjugate().T ) def __magic_name__ ( __a : np.ndarray , __a : np.ndarray ): '''simple docstring''' UpperCamelCase__ = v.conjugate().T UpperCamelCase__ = v_star.dot(__a ) assert isinstance(__a , np.ndarray ) return (v_star_dot.dot(__a )) / (v_star.dot(__a )) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) UpperCamelCase__ = np.array([[1], [2], [3]] ) assert is_hermitian(__a ), f"{a} is not hermitian." print(rayleigh_quotient(__a , __a ) ) UpperCamelCase__ = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(__a ), f"{a} is not hermitian." assert rayleigh_quotient(__a , __a ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __A( unittest.TestCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=18 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=4_00 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase__ = size if size is not None else {"""height""": 18, """width""": 18} UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = num_channels UpperCamelCase__ = image_size UpperCamelCase__ = min_resolution UpperCamelCase__ = max_resolution UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = apply_ocr def UpperCAmelCase_ (self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase_ (self ): UpperCamelCase__ = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase_ (self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """apply_ocr""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) UpperCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(encoding.boxes , SCREAMING_SNAKE_CASE_ ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def UpperCAmelCase_ (self ): # with apply_OCR = True UpperCamelCase__ = LayoutLMvaImageProcessor() from datasets import load_dataset UpperCamelCase__ = load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) UpperCamelCase__ = Image.open(ds[0]["""file"""] ).convert("""RGB""" ) UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 UpperCamelCase__ = [["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 UpperCamelCase__ = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(encoding.boxes , SCREAMING_SNAKE_CASE_ ) # with apply_OCR = False UpperCamelCase__ = LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __magic_name__ ( __a : ndarray ): '''simple docstring''' return np.dot(__a , __a ) class __A: """simple docstring""" def __init__(self , *, SCREAMING_SNAKE_CASE_ = np.inf , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = 0.0 , ): UpperCamelCase__ = regularization UpperCamelCase__ = gamma if kernel == "linear": UpperCamelCase__ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) UpperCamelCase__ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCamelCase__ = F"Unknown kernel: {kernel}" raise ValueError(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = observations UpperCamelCase__ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCamelCase__) , ) = np.shape(SCREAMING_SNAKE_CASE_ ) def to_minimize(SCREAMING_SNAKE_CASE_ ) -> float: UpperCamelCase__ = 0 ((UpperCamelCase__) , ) = np.shape(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(SCREAMING_SNAKE_CASE_ ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = LinearConstraint(SCREAMING_SNAKE_CASE_ , 0 , 0 ) UpperCamelCase__ = Bounds(0 , self.regularization ) UpperCamelCase__ = minimize( SCREAMING_SNAKE_CASE_ , np.ones(SCREAMING_SNAKE_CASE_ ) , bounds=SCREAMING_SNAKE_CASE_ , constraints=[ly_contraint] ).x UpperCamelCase__ = l_star # calculating mean offset of separation plane to points UpperCamelCase__ = 0 for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(SCREAMING_SNAKE_CASE_ ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCamelCase__ = s / n def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , SCREAMING_SNAKE_CASE_ ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
86
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): 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(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
1
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = 10 UpperCamelCase__ = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) UpperCamelCase__ = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(__a ) ), } , features=__a , ) return dataset @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Tuple , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=__a ) return filename # FILE_CONTENT + files lowerCamelCase_ = '''\ Text data. Second line of data.''' @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt""" UpperCamelCase__ = FILE_CONTENT with open(__a , """w""" ) as f: f.write(__a ) return filename @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : str ): '''simple docstring''' import bza UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" UpperCamelCase__ = bytes(__a , """utf-8""" ) with bza.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' import gzip UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) UpperCamelCase__ = bytes(__a , """utf-8""" ) with gzip.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Any ): '''simple docstring''' if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" UpperCamelCase__ = bytes(__a , """utf-8""" ) with lza.frame.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict , __a : Any ): '''simple docstring''' if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(__a , """w""" ) as archive: archive.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] , __a : int ): '''simple docstring''' import tarfile UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(__a , """w""" ) as f: f.add(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Any ): '''simple docstring''' import lzma UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" UpperCamelCase__ = bytes(__a , """utf-8""" ) with lzma.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[Any] , __a : str ): '''simple docstring''' import zipfile UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict ): '''simple docstring''' if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" UpperCamelCase__ = bytes(__a , """utf-8""" ) with zstd.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """file.xml""" UpperCamelCase__ = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(__a , """w""" ) as f: f.write(__a ) return filename lowerCamelCase_ = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] lowerCamelCase_ = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] lowerCamelCase_ = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } lowerCamelCase_ = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] lowerCamelCase_ = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope="""session""" ) def __magic_name__ ( ): '''simple docstring''' return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = datasets.Dataset.from_dict(__a ) UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(__a ) ) as con: UpperCamelCase__ = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(__a , """w""" , newline="""""" ) as f: UpperCamelCase__ = csv.DictWriter(__a , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(__a , """w""" , newline="""""" ) as f: UpperCamelCase__ = csv.DictWriter(__a , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] , __a : Union[str, Any] ): '''simple docstring''' import bza UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(__a , """rb""" ) as f: UpperCamelCase__ = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__a , """wb""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] , __a : List[str] , __a : Dict ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] , __a : List[str] , __a : Dict ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(__a , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : str , __a : Tuple , __a : Any ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) UpperCamelCase__ = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(__a , """wb""" ) as f: UpperCamelCase__ = pq.ParquetWriter(__a , schema=__a ) UpperCamelCase__ = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__a ) )] for k in DATA[0]} , schema=__a ) writer.write_table(__a ) writer.close() return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCamelCase__ = {"""data""": DATA} with open(__a , """w""" ) as f: json.dump(__a , __a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCamelCase__ = {"""data""": DATA_DICT_OF_LISTS} with open(__a , """w""" ) as f: json.dump(__a , __a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(__a , """w""" ) as f: for item in DATA: f.write(json.dumps(__a ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(__a , """w""" ) as f: for item in DATA: f.write(json.dumps(__a ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(__a , """w""" ) as f: for item in DATA_312: f.write(json.dumps(__a ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(__a , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(__a ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import gzip UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(__a , """rb""" ) as orig_file: with gzip.open(__a , """wb""" ) as zipped_file: zipped_file.writelines(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Union[str, Any] , __a : int ): '''simple docstring''' import gzip UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(__a , """rb""" ) as orig_file: with gzip.open(__a , """wb""" ) as zipped_file: zipped_file.writelines(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] , __a : Any , __a : int ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict , __a : Union[str, Any] , __a : Dict , __a : str ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.join("""nested""" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] , __a : Optional[int] , __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] , __a : Dict , __a : Dict ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(__a , """w""" ) as f: f.add(__a , arcname=os.path.basename(__a ) ) f.add(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] , __a : Any , __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(__a , """w""" ) as f: f.add(__a , arcname=os.path.join("""nested""" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""0""", """1""", """2""", """3"""] UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(__a , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = ["""0""", """1""", """2""", """3"""] UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(__a , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = ["""0""", """1""", """2""", """3"""] UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(__a , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[Any] , __a : Tuple , __a : str ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict , __a : List[str] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) f.write(__a , arcname=os.path.join("""main_dir""" , os.path.basename(__a ) ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : List[Any] , __a : Tuple , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(__a , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) UpperCamelCase__ = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(__a , """w""" , encoding="""utf-8""" ) as f: f.write(__a ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( ): '''simple docstring''' return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def __magic_name__ ( ): '''simple docstring''' return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : int , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(__a , """w""" ) as f: f.write(__a , arcname=os.path.basename(__a ) ) f.write(__a , arcname=os.path.basename(__a ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
86
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
1
def __magic_name__ ( __a : int ): '''simple docstring''' if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(__a , __a ): raise TypeError("""Input value must be a 'int' type""" ) return bin(__a ).count("""1""" ) if __name__ == "__main__": import doctest doctest.testmod()
86
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 __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 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()
86
1
def __magic_name__ ( __a : list[int] ): '''simple docstring''' UpperCamelCase__ = [] if len(__a ) == 1: return [nums.copy()] for _ in range(len(__a ) ): UpperCamelCase__ = nums.pop(0 ) UpperCamelCase__ = permute(__a ) for perm in permutations: perm.append(__a ) result.extend(__a ) nums.append(__a ) return result def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' def backtrack(__a : Tuple ): if start == len(__a ) - 1: output.append(nums[:] ) else: for i in range(__a , len(__a ) ): UpperCamelCase__ , UpperCamelCase__ = nums[i], nums[start] backtrack(start + 1 ) UpperCamelCase__ , UpperCamelCase__ = nums[i], nums[start] # backtrack UpperCamelCase__ = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function lowerCamelCase_ = permutea([1, 2, 3]) print(res) doctest.testmod()
86
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
1
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCamelCase_ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase_ = direct_transformers_import(PATH_TO_TRANSFORMERS) lowerCamelCase_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCamelCase_ = re.compile(r'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCamelCase_ = { '''DecisionTransformerConfig''', '''EncoderDecoderConfig''', '''MusicgenConfig''', '''RagConfig''', '''SpeechEncoderDecoderConfig''', '''TimmBackboneConfig''', '''VisionEncoderDecoderConfig''', '''VisionTextDualEncoderConfig''', '''LlamaConfig''', } def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = None # source code of `config_class` UpperCamelCase__ = inspect.getsource(__a ) UpperCamelCase__ = _re_checkpoint.findall(__a ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): UpperCamelCase__ = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase__ = f"https://huggingface.co/{ckpt_name}" if ckpt_link == ckpt_link_from_name: UpperCamelCase__ = ckpt_name break return checkpoint def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCamelCase__ = get_checkpoint_from_config_class(__a ) UpperCamelCase__ = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(__a ) if len(__a ) > 0: UpperCamelCase__ = """\n""".join(sorted(__a ) ) raise ValueError(f"The following configurations don't contain any valid checkpoint:\n{message}" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
import re from filelock import FileLock try: import nltk lowerCamelCase_ = True except (ImportError, ModuleNotFoundError): lowerCamelCase_ = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def __magic_name__ ( __a : str ): '''simple docstring''' re.sub("""<n>""" , """""" , __a ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__a ) )
86
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size 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__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): 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] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
1
import glob import os import random from string import ascii_lowercase, digits import cva lowerCamelCase_ = '''''' lowerCamelCase_ = '''''' lowerCamelCase_ = '''''' lowerCamelCase_ = 1 # (0 is vertical, 1 is horizontal) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = get_dataset(__a , __a ) print("""Processing...""" ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = update_image_and_anno(__a , __a , __a ) for index, image in enumerate(__a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' UpperCamelCase__ = random_chars(32 ) UpperCamelCase__ = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] UpperCamelCase__ = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cva.imwrite(f"/{file_root}.jpg" , __a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"Success {index+1}/{len(__a )} with {file_name}" ) UpperCamelCase__ = [] for anno in new_annos[index]: UpperCamelCase__ = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(__a ) with open(f"/{file_root}.txt" , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = [] for label_file in glob.glob(os.path.join(__a , """*.txt""" ) ): UpperCamelCase__ = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__a ) as in_file: UpperCamelCase__ = in_file.readlines() UpperCamelCase__ = os.path.join(__a , f"{label_name}.jpg" ) UpperCamelCase__ = [] for obj_list in obj_lists: UpperCamelCase__ = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__a ) labels.append(__a ) return img_paths, labels def __magic_name__ ( __a : list , __a : list , __a : int = 1 ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = [] for idx in range(len(__a ) ): UpperCamelCase__ = [] UpperCamelCase__ = img_list[idx] path_list.append(__a ) UpperCamelCase__ = anno_list[idx] UpperCamelCase__ = cva.imread(__a ) if flip_type == 1: UpperCamelCase__ = cva.flip(__a , __a ) for bbox in img_annos: UpperCamelCase__ = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: UpperCamelCase__ = cva.flip(__a , __a ) for bbox in img_annos: UpperCamelCase__ = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__a ) new_imgs_list.append(__a ) return new_imgs_list, new_annos_lists, path_list def __magic_name__ ( __a : int = 32 ): '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" UpperCamelCase__ = ascii_lowercase + digits return "".join(random.choice(__a ) for _ in range(__a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
86
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
1
def __magic_name__ ( __a : List[Any] ): '''simple docstring''' if collection == []: return [] # get some information about the collection UpperCamelCase__ = len(__a ) UpperCamelCase__ = max(__a ) UpperCamelCase__ = min(__a ) # create the counting array UpperCamelCase__ = coll_max + 1 - coll_min UpperCamelCase__ = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , __a ): UpperCamelCase__ = counting_arr[i] + counting_arr[i - 1] # create the output collection UpperCamelCase__ = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , __a ) ): UpperCamelCase__ = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def __magic_name__ ( __a : Dict ): '''simple docstring''' return "".join([chr(__a ) for i in counting_sort([ord(__a ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" lowerCamelCase_ = input('''Enter numbers separated by a comma:\n''').strip() lowerCamelCase_ = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
86
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
1
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def __magic_name__ ( __a : Any ): '''simple docstring''' if "img_encoder.pos_embed" in name: UpperCamelCase__ = name.replace("""img_encoder.pos_embed""" , """vision_model.embeddings.position_embeddings""" ) if "img_encoder.patch_embed.proj" in name: UpperCamelCase__ = name.replace("""img_encoder.patch_embed.proj""" , """vision_model.embeddings.patch_embeddings.projection""" ) if "img_encoder.patch_embed.norm" in name: UpperCamelCase__ = name.replace("""img_encoder.patch_embed.norm""" , """vision_model.embeddings.layernorm""" ) if "img_encoder.layers" in name: UpperCamelCase__ = name.replace("""img_encoder.layers""" , """vision_model.encoder.stages""" ) if "blocks" in name and "res" not in name: UpperCamelCase__ = name.replace("""blocks""" , """layers""" ) if "attn" in name and "pre_assign" not in name: UpperCamelCase__ = name.replace("""attn""" , """self_attn""" ) if "proj" in name and "self_attn" in name and "text" not in name: UpperCamelCase__ = name.replace("""proj""" , """out_proj""" ) if "pre_assign_attn.attn.proj" in name: UpperCamelCase__ = name.replace("""pre_assign_attn.attn.proj""" , """pre_assign_attn.attn.out_proj""" ) if "norm1" in name: UpperCamelCase__ = name.replace("""norm1""" , """layer_norm1""" ) if "norm2" in name and "pre_assign" not in name: UpperCamelCase__ = name.replace("""norm2""" , """layer_norm2""" ) if "img_encoder.norm" in name: UpperCamelCase__ = name.replace("""img_encoder.norm""" , """vision_model.layernorm""" ) # text encoder if "text_encoder.token_embedding" in name: UpperCamelCase__ = name.replace("""text_encoder.token_embedding""" , """text_model.embeddings.token_embedding""" ) if "text_encoder.positional_embedding" in name: UpperCamelCase__ = name.replace("""text_encoder.positional_embedding""" , """text_model.embeddings.position_embedding.weight""" ) if "text_encoder.transformer.resblocks." in name: UpperCamelCase__ = name.replace("""text_encoder.transformer.resblocks.""" , """text_model.encoder.layers.""" ) if "ln_1" in name: UpperCamelCase__ = name.replace("""ln_1""" , """layer_norm1""" ) if "ln_2" in name: UpperCamelCase__ = name.replace("""ln_2""" , """layer_norm2""" ) if "c_fc" in name: UpperCamelCase__ = name.replace("""c_fc""" , """fc1""" ) if "c_proj" in name: UpperCamelCase__ = name.replace("""c_proj""" , """fc2""" ) if "text_encoder" in name: UpperCamelCase__ = name.replace("""text_encoder""" , """text_model""" ) if "ln_final" in name: UpperCamelCase__ = name.replace("""ln_final""" , """final_layer_norm""" ) # projection layers if "img_projector.linear_hidden." in name: UpperCamelCase__ = name.replace("""img_projector.linear_hidden.""" , """visual_projection.""" ) if "img_projector.linear_out." in name: UpperCamelCase__ = name.replace("""img_projector.linear_out.""" , """visual_projection.3.""" ) if "text_projector.linear_hidden" in name: UpperCamelCase__ = name.replace("""text_projector.linear_hidden""" , """text_projection""" ) if "text_projector.linear_out" in name: UpperCamelCase__ = name.replace("""text_projector.linear_out""" , """text_projection.3""" ) return name def __magic_name__ ( __a : Union[str, Any] , __a : Tuple ): '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(__a ) 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 UpperCamelCase__ = key.split(""".""" ) UpperCamelCase__ , UpperCamelCase__ = int(key_split[2] ), int(key_split[4] ) UpperCamelCase__ = config.vision_config.hidden_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[dim : dim * 2, :] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[:dim] UpperCamelCase__ = val[dim : dim * 2] UpperCamelCase__ = 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 UpperCamelCase__ = key.split(""".""" ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = config.text_config.hidden_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[:dim] UpperCamelCase__ = val[dim : dim * 2] UpperCamelCase__ = val[-dim:] else: UpperCamelCase__ = rename_key(__a ) # 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 ): UpperCamelCase__ = val.squeeze_() else: UpperCamelCase__ = val return orig_state_dict def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase__ = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def __magic_name__ ( __a : List[str] , __a : int , __a : Union[str, Any]="groupvit-gcc-yfcc" , __a : Optional[int]=False ): '''simple docstring''' UpperCamelCase__ = GroupViTConfig() UpperCamelCase__ = GroupViTModel(__a ).eval() UpperCamelCase__ = torch.load(__a , map_location="""cpu""" )["""model"""] UpperCamelCase__ = convert_state_dict(__a , __a ) UpperCamelCase__ , UpperCamelCase__ = model.load_state_dict(__a , strict=__a ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(__a ) == 0) # verify result UpperCamelCase__ = CLIPProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) UpperCamelCase__ = prepare_img() UpperCamelCase__ = processor(text=["""a photo of a cat""", """a photo of a dog"""] , images=__a , padding=__a , return_tensors="""pt""" ) with torch.no_grad(): UpperCamelCase__ = model(**__a ) if model_name == "groupvit-gcc-yfcc": UpperCamelCase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": UpperCamelCase__ = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(f"Model name {model_name} not supported." ) assert torch.allclose(outputs.logits_per_image , __a , atol=1E-3 ) processor.save_pretrained(__a ) model.save_pretrained(__a ) print("""Successfully saved processor and model to""" , __a ) if push_to_hub: print("""Pushing to the hub...""" ) processor.push_to_hub(__a , organization="""nielsr""" ) model.push_to_hub(__a , organization="""nielsr""" ) if __name__ == "__main__": lowerCamelCase_ = 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`.''', ) lowerCamelCase_ = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return F"gaussian_noise_s={seed}_shape={'_'.join([str(SCREAMING_SNAKE_CASE_ ) for s in shape] )}.npy" def UpperCAmelCase_ (self ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=(4, 4, 64, 64) , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase__ = jnp.array(load_hf_numpy(self.get_file_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , dtype=SCREAMING_SNAKE_CASE_ ) return image def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="CompVis/stable-diffusion-v1-4" ): UpperCamelCase__ = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase__ = """bf16""" if fpaa else None UpperCamelCase__ , UpperCamelCase__ = FlaxUNetaDConditionModel.from_pretrained( SCREAMING_SNAKE_CASE_ , subfolder="""unet""" , dtype=SCREAMING_SNAKE_CASE_ , revision=SCREAMING_SNAKE_CASE_ ) return model, params def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=(4, 77, 7_68) , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase__ = jnp.array(load_hf_numpy(self.get_file_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , dtype=SCREAMING_SNAKE_CASE_ ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]], [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]], [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]], [3, 10_00, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]], # fmt: on ] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ , UpperCamelCase__ = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_latents(SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_encoder_hidden_states(SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.apply( {"""params""": params} , SCREAMING_SNAKE_CASE_ , jnp.array(SCREAMING_SNAKE_CASE_ , dtype=jnp.intaa ) , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , ).sample assert sample.shape == latents.shape UpperCamelCase__ = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCamelCase__ = jnp.array(SCREAMING_SNAKE_CASE_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]], [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]], [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]], [3, 10_00, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]], # fmt: on ] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ , UpperCamelCase__ = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_latents(SCREAMING_SNAKE_CASE_ , shape=(4, 4, 96, 96) , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_encoder_hidden_states(SCREAMING_SNAKE_CASE_ , shape=(4, 77, 10_24) , fpaa=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.apply( {"""params""": params} , SCREAMING_SNAKE_CASE_ , jnp.array(SCREAMING_SNAKE_CASE_ , dtype=jnp.intaa ) , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , ).sample assert sample.shape == latents.shape UpperCamelCase__ = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCamelCase__ = jnp.array(SCREAMING_SNAKE_CASE_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-2 )
86
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
1
from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = '''T5Config''' class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """mt5""" SCREAMING_SNAKE_CASE__ = MTaConfig class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """mt5""" SCREAMING_SNAKE_CASE__ = MTaConfig class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """mt5""" SCREAMING_SNAKE_CASE__ = MTaConfig
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
from typing import List import numpy as np def __magic_name__ ( __a : dict ): '''simple docstring''' UpperCamelCase__ = {key: len(__a ) for key, value in gen_kwargs.items() if isinstance(__a , __a )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( """Sharding is ambiguous for this dataset: """ + """we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n""" + """\n""".join(f"\t- key {key} has length {length}" for key, length in lists_lengths.items() ) + """\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, """ + """and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.""" ) ) UpperCamelCase__ = max(lists_lengths.values() , default=0 ) return max(1 , __a ) def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = [] for group_idx in range(__a ): UpperCamelCase__ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break UpperCamelCase__ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 UpperCamelCase__ = range(__a , start + num_shards_to_add ) shards_indices_per_group.append(__a ) return shards_indices_per_group def __magic_name__ ( __a : dict , __a : int ): '''simple docstring''' UpperCamelCase__ = _number_of_shards_in_gen_kwargs(__a ) if num_shards == 1: return [dict(__a )] else: UpperCamelCase__ = _distribute_shards(num_shards=__a , max_num_jobs=__a ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(__a , __a ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(__a ) ) ] def __magic_name__ ( __a : List[dict] ): '''simple docstring''' return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , __a ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def __magic_name__ ( __a : np.random.Generator , __a : dict ): '''simple docstring''' UpperCamelCase__ = {len(__a ) for value in gen_kwargs.values() if isinstance(__a , __a )} UpperCamelCase__ = {} for size in list_sizes: UpperCamelCase__ = list(range(__a ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes UpperCamelCase__ = dict(__a ) for key, value in shuffled_kwargs.items(): if isinstance(__a , __a ): UpperCamelCase__ = [value[i] for i in indices_per_size[len(__a )]] return shuffled_kwargs
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @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 __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase_ = {'''configuration_vit''': ['''VIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTConfig''', '''ViTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''ViTFeatureExtractor'''] lowerCamelCase_ = ['''ViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''VIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTForImageClassification''', '''ViTForMaskedImageModeling''', '''ViTModel''', '''ViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TFViTForImageClassification''', '''TFViTModel''', '''TFViTPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''FlaxViTForImageClassification''', '''FlaxViTModel''', '''FlaxViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
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 lowerCamelCase_ = '''true''' def __magic_name__ ( __a : Tuple , __a : Tuple=82 , __a : Optional[Any]=16 ): '''simple docstring''' set_seed(42 ) UpperCamelCase__ = RegressionModel() UpperCamelCase__ = deepcopy(__a ) UpperCamelCase__ = RegressionDataset(length=__a ) UpperCamelCase__ = DataLoader(__a , batch_size=__a ) model.to(accelerator.device ) UpperCamelCase__ , UpperCamelCase__ = accelerator.prepare(__a , __a ) return model, ddp_model, dataloader def __magic_name__ ( __a : Accelerator , __a : Union[str, Any]=False ): '''simple docstring''' UpperCamelCase__ = AutoTokenizer.from_pretrained("""hf-internal-testing/mrpc-bert-base-cased""" ) UpperCamelCase__ = load_dataset("""glue""" , """mrpc""" , split="""validation""" ) def tokenize_function(__a : Any ): UpperCamelCase__ = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__a , max_length=__a ) return outputs with accelerator.main_process_first(): UpperCamelCase__ = dataset.map( __a , batched=__a , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) UpperCamelCase__ = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__a : int ): if use_longest: return tokenizer.pad(__a , padding="""longest""" , return_tensors="""pt""" ) return tokenizer.pad(__a , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return DataLoader(__a , shuffle=__a , collate_fn=__a , batch_size=16 ) def __magic_name__ ( __a : int , __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = Accelerator(dispatch_batches=__a , split_batches=__a ) UpperCamelCase__ = get_dataloader(__a , not dispatch_batches ) UpperCamelCase__ = AutoModelForSequenceClassification.from_pretrained( """hf-internal-testing/mrpc-bert-base-cased""" , return_dict=__a ) UpperCamelCase__ , UpperCamelCase__ = accelerator.prepare(__a , __a ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __magic_name__ ( __a : Union[str, Any] , __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = [] for batch in dataloader: UpperCamelCase__ , UpperCamelCase__ = batch.values() with torch.no_grad(): UpperCamelCase__ = model(__a ) UpperCamelCase__ , UpperCamelCase__ = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) UpperCamelCase__ , UpperCamelCase__ = [], [] for logit, targ in logits_and_targets: logits.append(__a ) targs.append(__a ) UpperCamelCase__ , UpperCamelCase__ = torch.cat(__a ), torch.cat(__a ) return logits, targs def __magic_name__ ( __a : Accelerator , __a : Any=82 , __a : Any=False , __a : Tuple=False , __a : str=16 ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = get_basic_setup(__a , __a , __a ) UpperCamelCase__ , UpperCamelCase__ = generate_predictions(__a , __a , __a ) assert ( len(__a ) == num_samples ), f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__a )}" def __magic_name__ ( __a : bool = False , __a : bool = False ): '''simple docstring''' UpperCamelCase__ = evaluate.load("""glue""" , """mrpc""" ) UpperCamelCase__ , UpperCamelCase__ = get_mrpc_setup(__a , __a ) # First do baseline UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = setup["""no"""] model.to(__a ) model.eval() for batch in dataloader: batch.to(__a ) with torch.inference_mode(): UpperCamelCase__ = model(**__a ) UpperCamelCase__ = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=__a , references=batch["""labels"""] ) UpperCamelCase__ = metric.compute() # Then do distributed UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = setup["""ddp"""] model.eval() for batch in dataloader: with torch.inference_mode(): UpperCamelCase__ = model(**__a ) UpperCamelCase__ = outputs.logits.argmax(dim=-1 ) UpperCamelCase__ = batch["""labels"""] UpperCamelCase__ , UpperCamelCase__ = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=__a , references=__a ) UpperCamelCase__ = 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 __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Accelerator(split_batches=__a , dispatch_batches=__a ) 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(__a , __a ) 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]: UpperCamelCase__ = Accelerator(split_batches=__a , dispatch_batches=__a ) if accelerator.is_local_main_process: print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99" ) test_torch_metrics(__a , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test last batch is not dropped when perfectly divisible**""" ) UpperCamelCase__ = Accelerator() test_torch_metrics(__a , 512 ) accelerator.state._reset_state() def __magic_name__ ( __a : str ): '''simple docstring''' main() if __name__ == "__main__": main()
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = { '''configuration_bert''': ['''BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BertConfig''', '''BertOnnxConfig'''], '''tokenization_bert''': ['''BasicTokenizer''', '''BertTokenizer''', '''WordpieceTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''BertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BertForMaskedLM''', '''BertForMultipleChoice''', '''BertForNextSentencePrediction''', '''BertForPreTraining''', '''BertForQuestionAnswering''', '''BertForSequenceClassification''', '''BertForTokenClassification''', '''BertLayer''', '''BertLMHeadModel''', '''BertModel''', '''BertPreTrainedModel''', '''load_tf_weights_in_bert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBertEmbeddings''', '''TFBertForMaskedLM''', '''TFBertForMultipleChoice''', '''TFBertForNextSentencePrediction''', '''TFBertForPreTraining''', '''TFBertForQuestionAnswering''', '''TFBertForSequenceClassification''', '''TFBertForTokenClassification''', '''TFBertLMHeadModel''', '''TFBertMainLayer''', '''TFBertModel''', '''TFBertPreTrainedModel''', ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''TFBertTokenizer'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''FlaxBertForCausalLM''', '''FlaxBertForMaskedLM''', '''FlaxBertForMultipleChoice''', '''FlaxBertForNextSentencePrediction''', '''FlaxBertForPreTraining''', '''FlaxBertForQuestionAnswering''', '''FlaxBertForSequenceClassification''', '''FlaxBertForTokenClassification''', '''FlaxBertModel''', '''FlaxBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel lowerCamelCase_ = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class __A( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase_ (cls ): UpperCamelCase__ = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase_ (cls ): try: delete_repo(token=cls._token , repo_id="""test-model-flax""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-model-flax-org""" ) except HTTPError: pass def UpperCAmelCase_ (self ): UpperCamelCase__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ ) model.push_to_hub("""test-model-flax""" , use_auth_token=self._token ) UpperCamelCase__ = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) UpperCamelCase__ = flatten_dict(unfreeze(model.params ) ) UpperCamelCase__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="""test-model-flax""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE_ , repo_id="""test-model-flax""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase__ = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) UpperCamelCase__ = flatten_dict(unfreeze(model.params ) ) UpperCamelCase__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 , msg=F"{key} not identical" ) def UpperCAmelCase_ (self ): UpperCamelCase__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ ) model.push_to_hub("""valid_org/test-model-flax-org""" , use_auth_token=self._token ) UpperCamelCase__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) UpperCamelCase__ = flatten_dict(unfreeze(model.params ) ) UpperCamelCase__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-model-flax-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id="""valid_org/test-model-flax-org""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) UpperCamelCase__ = flatten_dict(unfreeze(model.params ) ) UpperCamelCase__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): UpperCamelCase__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 , msg=F"{key} not identical" ) def __magic_name__ ( __a : Union[str, Any] , __a : Dict ): '''simple docstring''' UpperCamelCase__ = True UpperCamelCase__ = flatten_dict(modela.params ) UpperCamelCase__ = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: UpperCamelCase__ = False return models_are_equal @require_flax class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder=SCREAMING_SNAKE_CASE_ ) self.assertTrue(check_models_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , max_shard_size="""10KB""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder=SCREAMING_SNAKE_CASE_ ) self.assertTrue(check_models_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = """bert""" UpperCamelCase__ = """hf-internal-testing/tiny-random-bert-subfolder""" with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = """bert""" UpperCamelCase__ = """hf-internal-testing/tiny-random-bert-sharded-subfolder""" with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {name: getattr(transformers, name + '''Fast''') for name in SLOW_TO_FAST_CONVERTERS} def __magic_name__ ( __a : Optional[int] , __a : Any , __a : Union[str, Any] , __a : Dict ): '''simple docstring''' if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}." ) if tokenizer_name is None: UpperCamelCase__ = TOKENIZER_CLASSES else: UpperCamelCase__ = {tokenizer_name: getattr(__a , tokenizer_name + """Fast""" )} logger.info(f"Loading tokenizer classes: {tokenizer_names}" ) for tokenizer_name in tokenizer_names: UpperCamelCase__ = TOKENIZER_CLASSES[tokenizer_name] UpperCamelCase__ = True if checkpoint_name is None: UpperCamelCase__ = list(tokenizer_class.max_model_input_sizes.keys() ) else: UpperCamelCase__ = [checkpoint_name] logger.info(f"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}" ) for checkpoint in checkpoint_names: logger.info(f"Loading {tokenizer_class.__class__.__name__} {checkpoint}" ) # Load tokenizer UpperCamelCase__ = tokenizer_class.from_pretrained(__a , force_download=__a ) # Save fast tokenizer logger.info(f"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}" ) # For organization names we create sub-directories if "/" in checkpoint: UpperCamelCase__ , UpperCamelCase__ = checkpoint.split("""/""" ) UpperCamelCase__ = os.path.join(__a , __a ) elif add_prefix: UpperCamelCase__ = checkpoint UpperCamelCase__ = dump_path else: UpperCamelCase__ = None UpperCamelCase__ = dump_path logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: UpperCamelCase__ = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] UpperCamelCase__ = file_path.split(__a )[-1][0] if next_char == "/": UpperCamelCase__ = os.path.join(__a , __a ) UpperCamelCase__ = None logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) UpperCamelCase__ = tokenizer.save_pretrained( __a , legacy_format=__a , filename_prefix=__a ) logger.info(f"=> File names {file_names}" ) for file_name in file_names: if not file_name.endswith("""tokenizer.json""" ): os.remove(__a ) logger.info(f"=> removing {file_name}" ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output generated fast tokenizer files.''' ) parser.add_argument( '''--tokenizer_name''', default=None, type=str, help=( f'Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ' '''download and convert all the checkpoints from AWS.''' ), ) parser.add_argument( '''--checkpoint_name''', default=None, type=str, help='''Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.''', ) parser.add_argument( '''--force_download''', action='''store_true''', help='''Re-download checkpoints.''', ) lowerCamelCase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase_ = { '''configuration_m2m_100''': ['''M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''M2M100Config''', '''M2M100OnnxConfig'''], '''tokenization_m2m_100''': ['''M2M100Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST''', '''M2M100ForConditionalGeneration''', '''M2M100Model''', '''M2M100PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
86
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): 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(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
1
from copy import deepcopy class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None ): if arr is None and size is not None: UpperCamelCase__ = size UpperCamelCase__ = [0] * size elif arr is not None: self.init(SCREAMING_SNAKE_CASE_ ) else: raise ValueError("""Either arr or size must be specified""" ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = deepcopy(SCREAMING_SNAKE_CASE_ ) for i in range(1 , self.size ): UpperCamelCase__ = self.next_(SCREAMING_SNAKE_CASE_ ) if j < self.size: self.tree[j] += self.tree[i] def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): UpperCamelCase__ = self.next_(SCREAMING_SNAKE_CASE_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def UpperCAmelCase_ (SCREAMING_SNAKE_CASE_ ): return index + (index & (-index)) @staticmethod def UpperCAmelCase_ (SCREAMING_SNAKE_CASE_ ): return index - (index & (-index)) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCamelCase__ = self.next_(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.add(SCREAMING_SNAKE_CASE_ , value - self.get(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): if right == 0: return 0 UpperCamelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCamelCase__ = self.prev(SCREAMING_SNAKE_CASE_ ) return result def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return self.prefix(SCREAMING_SNAKE_CASE_ ) - self.prefix(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return self.query(SCREAMING_SNAKE_CASE_ , index + 1 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): value -= self.tree[0] if value < 0: return -1 UpperCamelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCamelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
86
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
1
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCamelCase_ = '''platform''' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = PegasusConfig SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = """gelu""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=20 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = eos_token_id UpperCamelCase__ = pad_token_id UpperCamelCase__ = bos_token_id def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) UpperCamelCase__ = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase__ = np.concatenate([input_ids, eos_tensor] , axis=1 ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = 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 , ) UpperCamelCase__ = prepare_pegasus_inputs_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 20 UpperCamelCase__ = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase__ , UpperCamelCase__ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase__ = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) UpperCamelCase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase__ = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase__ = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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 UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 20 UpperCamelCase__ = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase__ , UpperCamelCase__ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase__ = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCamelCase__ = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase__ = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase__ = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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 __magic_name__ ( __a : Optional[Any] , __a : Dict , __a : Tuple , __a : Any=None , __a : int=None , ): '''simple docstring''' if attention_mask is None: UpperCamelCase__ = np.not_equal(__a , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: UpperCamelCase__ = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) SCREAMING_SNAKE_CASE__ = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = FlaxPegasusModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): 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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) @jax.jit def encode_jitted(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): return model.encode(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) with self.subTest("""JIT Enabled""" ): UpperCamelCase__ = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase__ = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ (self ): 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__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) UpperCamelCase__ = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return model.decode( decoder_input_ids=SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , encoder_outputs=SCREAMING_SNAKE_CASE_ , ) with self.subTest("""JIT Enabled""" ): UpperCamelCase__ = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase__ = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ (self ): for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = np.ones((1, 1) ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) UpperCamelCase__ = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) 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 turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" , truncation=SCREAMING_SNAKE_CASE_ , max_length=5_12 , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(**SCREAMING_SNAKE_CASE_ , num_beams=2 ).sequences UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) assert tgt_text == decoded
86
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
1
def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' return [sentence[i : i + ngram_size] for i in range(len(__a ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
86
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 __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 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()
86
1
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (IPNDMScheduler,) SCREAMING_SNAKE_CASE__ = (("""num_inference_steps""", 50),) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = {"""num_train_timesteps""": 10_00} config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = dict(self.forward_default_kwargs ) UpperCamelCase__ = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.dummy_sample UpperCamelCase__ = 0.1 * sample UpperCamelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCamelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals UpperCamelCase__ = dummy_past_residuals[:] if time_step is None: UpperCamelCase__ = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals UpperCamelCase__ = dummy_past_residuals[:] UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = dict(self.forward_default_kwargs ) UpperCamelCase__ = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.dummy_sample UpperCamelCase__ = 0.1 * sample UpperCamelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals (must be after setting timesteps) UpperCamelCase__ = dummy_past_residuals[:] if time_step is None: UpperCamelCase__ = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residual (must be after setting timesteps) UpperCamelCase__ = dummy_past_residuals[:] UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 10 UpperCamelCase__ = self.dummy_model() UpperCamelCase__ = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample for i, t in enumerate(scheduler.timesteps ): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def UpperCAmelCase_ (self ): UpperCamelCase__ = dict(self.forward_default_kwargs ) UpperCamelCase__ = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ ) for scheduler_class in self.scheduler_classes: UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.dummy_sample UpperCamelCase__ = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE_ , """set_timesteps""" ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE_ , """set_timesteps""" ): UpperCamelCase__ = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) UpperCamelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] UpperCamelCase__ = dummy_past_residuals[:] UpperCamelCase__ = scheduler.timesteps[5] UpperCamelCase__ = scheduler.timesteps[6] UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase__ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase_ (self ): for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ , time_step=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE_ , time_step=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.full_loop() UpperCamelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 2_54_05_29 ) < 10
86
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
1
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 __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""image_processor""", """tokenizer"""] SCREAMING_SNAKE_CASE__ = """BlipImageProcessor""" SCREAMING_SNAKE_CASE__ = """AutoTokenizer""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # add QFormer tokenizer UpperCamelCase__ = qformer_tokenizer def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if images is None and text is None: raise ValueError("""You have to specify at least images or text.""" ) UpperCamelCase__ = BatchFeature() if text is not None: UpperCamelCase__ = self.tokenizer( text=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) encoding.update(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.qformer_tokenizer( text=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = qformer_text_encoding.pop("""input_ids""" ) UpperCamelCase__ = qformer_text_encoding.pop("""attention_mask""" ) if images is not None: UpperCamelCase__ = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) encoding.update(SCREAMING_SNAKE_CASE_ ) return encoding def UpperCAmelCase_ (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer.model_input_names UpperCamelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): if os.path.isfile(SCREAMING_SNAKE_CASE_ ): raise ValueError(F"Provided path ({save_directory}) should be a directory, not a file" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE_ , """qformer_tokenizer""" ) self.qformer_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) return super().save_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase_ (cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder="""qformer_tokenizer""" ) UpperCamelCase__ = cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) args.append(SCREAMING_SNAKE_CASE_ ) return cls(*SCREAMING_SNAKE_CASE_ )
86
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
1
lowerCamelCase_ = 6_55_21 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 0 for plain_chr in plain_text: UpperCamelCase__ = (a + ord(__a )) % MOD_ADLER UpperCamelCase__ = (b + a) % MOD_ADLER return (b << 16) | a
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @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 __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size 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__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): 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] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
1
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
1
from jiwer import compute_measures import datasets lowerCamelCase_ = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' lowerCamelCase_ = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' lowerCamelCase_ = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False ): if concatenate_texts: return compute_measures(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )["wer"] else: UpperCamelCase__ = 0 UpperCamelCase__ = 0 for prediction, reference in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = compute_measures(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
86
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class __A( unittest.TestCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=18 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=4_00 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=[0.4814_5466, 0.457_8275, 0.4082_1073] , SCREAMING_SNAKE_CASE_=[0.2686_2954, 0.2613_0258, 0.2757_7711] , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase__ = size if size is not None else {"""height""": 2_24, """width""": 2_24} UpperCamelCase__ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = num_channels UpperCamelCase__ = image_size UpperCamelCase__ = min_resolution UpperCamelCase__ = max_resolution UpperCamelCase__ = do_resize UpperCamelCase__ = size UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = do_normalize UpperCamelCase__ = image_mean UpperCamelCase__ = image_std UpperCamelCase__ = do_convert_rgb def UpperCAmelCase_ (self ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: UpperCamelCase__ = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_55 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: UpperCamelCase__ = [] for i in range(self.batch_size ): UpperCamelCase__ , UpperCamelCase__ = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(2_55 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension UpperCamelCase__ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] if torchify: UpperCamelCase__ = [torch.from_numpy(SCREAMING_SNAKE_CASE_ ) for x in image_inputs] return image_inputs @require_torch @require_vision class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ChineseCLIPImageProcessor if is_vision_available() else None def UpperCAmelCase_ (self ): UpperCamelCase__ = ChineseCLIPImageProcessingTester(self , do_center_crop=SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase_ (self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_convert_rgb""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 2_24, """width""": 2_24} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) UpperCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) @require_torch @require_vision class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ChineseCLIPImageProcessor if is_vision_available() else None def UpperCAmelCase_ (self ): UpperCamelCase__ = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 3 @property def UpperCAmelCase_ (self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_convert_rgb""" ) ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase__ = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
from __future__ import annotations from typing import Any class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0 ): UpperCamelCase__ , UpperCamelCase__ = row, column UpperCamelCase__ = [[default_value for c in range(SCREAMING_SNAKE_CASE_ )] for r in range(SCREAMING_SNAKE_CASE_ )] def __str__(self ): UpperCamelCase__ = F"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier UpperCamelCase__ = 0 for row_vector in self.array: for obj in row_vector: UpperCamelCase__ = max(SCREAMING_SNAKE_CASE_ , len(str(SCREAMING_SNAKE_CASE_ ) ) ) UpperCamelCase__ = F"%{max_element_length}s" # Make string and return def single_line(SCREAMING_SNAKE_CASE_ ) -> str: nonlocal string_format_identifier UpperCamelCase__ = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(SCREAMING_SNAKE_CASE_ ) for row_vector in self.array ) return s def __repr__(self ): return str(self ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): if not (isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and len(SCREAMING_SNAKE_CASE_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self , SCREAMING_SNAKE_CASE_ ): assert self.validate_indicies(SCREAMING_SNAKE_CASE_ ) return self.array[loc[0]][loc[1]] def __setitem__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): assert self.validate_indicies(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = value def __add__(self , SCREAMING_SNAKE_CASE_ ): assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert self.row == another.row and self.column == another.column # Add UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] + another[r, c] return result def __neg__(self ): UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = -self[r, c] return result def __sub__(self , SCREAMING_SNAKE_CASE_ ): return self + (-another) def __mul__(self , SCREAMING_SNAKE_CASE_ ): if isinstance(SCREAMING_SNAKE_CASE_ , (int, float) ): # Scalar multiplication UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] * another return result elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # Matrix multiplication assert self.column == another.row UpperCamelCase__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: UpperCamelCase__ = F"Unsupported type given for another ({type(SCREAMING_SNAKE_CASE_ )})" raise TypeError(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] return result def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate UpperCamelCase__ = v.transpose() UpperCamelCase__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Matrix(3 , 3 , 0 ) for i in range(3 ): UpperCamelCase__ = 1 print(f"a^(-1) is {ainv}" ) # u, v UpperCamelCase__ = Matrix(3 , 1 , 0 ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 1, 2, -3 UpperCamelCase__ = Matrix(3 , 1 , 0 ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 4, -2, 5 print(f"u is {u}" ) print(f"v is {v}" ) print(f"uv^T is {u * v.transpose()}" ) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(__a , __a )}" ) def __magic_name__ ( ): '''simple docstring''' import doctest doctest.testmod() testa()
86
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
1
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () lowerCamelCase_ = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). lowerCamelCase_ = [0, 25, 50] lowerCamelCase_ = [25, 50, 75] lowerCamelCase_ = fuzz.membership.trimf(X, abca) lowerCamelCase_ = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. lowerCamelCase_ = np.ones(75) lowerCamelCase_ = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) lowerCamelCase_ = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) lowerCamelCase_ = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) lowerCamelCase_ = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) lowerCamelCase_ = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] lowerCamelCase_ = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) lowerCamelCase_ = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] lowerCamelCase_ = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] lowerCamelCase_ = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('''Young''') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('''Middle aged''') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('''union''') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('''intersection''') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('''complement_a''') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('''difference a/b''') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('''alg_sum''') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('''alg_product''') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('''bdd_sum''') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('''bdd_difference''') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """trocr""" SCREAMING_SNAKE_CASE__ = ["""past_key_values"""] SCREAMING_SNAKE_CASE__ = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__(self , SCREAMING_SNAKE_CASE_=5_02_65 , SCREAMING_SNAKE_CASE_=10_24 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=40_96 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = vocab_size UpperCamelCase__ = d_model UpperCamelCase__ = decoder_layers UpperCamelCase__ = decoder_attention_heads UpperCamelCase__ = decoder_ffn_dim UpperCamelCase__ = activation_function UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = activation_dropout UpperCamelCase__ = init_std UpperCamelCase__ = decoder_layerdrop UpperCamelCase__ = use_cache UpperCamelCase__ = scale_embedding UpperCamelCase__ = use_learned_position_embeddings UpperCamelCase__ = layernorm_embedding super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING lowerCamelCase_ = logging.get_logger(__name__) @add_end_docstrings(__lowerCamelCase ) class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) requires_backends(self , """vision""" ) self.check_model_type(SCREAMING_SNAKE_CASE_ ) def __call__(self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return super().__call__(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return {}, {}, {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = load_image(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.size UpperCamelCase__ = self.image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors=self.framework ) return model_inputs def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.model(**SCREAMING_SNAKE_CASE_ ) return model_outputs def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = model_outputs.predicted_depth UpperCamelCase__ = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode="""bicubic""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = prediction.squeeze().cpu().numpy() UpperCamelCase__ = (output * 2_55 / np.max(SCREAMING_SNAKE_CASE_ )).astype("""uint8""" ) UpperCamelCase__ = Image.fromarray(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = {} UpperCamelCase__ = predicted_depth UpperCamelCase__ = depth return output_dict
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @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 __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { '''configuration_pegasus_x''': ['''PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PegasusXConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PegasusXForConditionalGeneration''', '''PegasusXModel''', '''PegasusXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): 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(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def __magic_name__ ( __a : str , __a : str , **__a : Tuple ): '''simple docstring''' UpperCamelCase__ = AutoConfig.from_pretrained(__a , **__a ) UpperCamelCase__ = AutoModelForSeqaSeqLM.from_config(__a ) model.save_pretrained(__a ) AutoTokenizer.from_pretrained(__a ).save_pretrained(__a ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
from __future__ import annotations def __magic_name__ ( __a : list[int] , __a : int ): '''simple docstring''' if len(__a ) < k or k < 0: raise ValueError("""Invalid Input""" ) UpperCamelCase__ = UpperCamelCase__ = sum(array[:k] ) for i in range(len(__a ) - k ): UpperCamelCase__ = current_sum - array[i] + array[i + k] UpperCamelCase__ = max(__a , __a ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() lowerCamelCase_ = [randint(-10_00, 10_00) for i in range(1_00)] lowerCamelCase_ = randint(0, 1_10) print(f'The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}')
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1