code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def _a ( a :int ) -> Tuple: a = [] a = set({'''(''', '''[''', '''{'''} ) a = set({''')''', ''']''', '''}'''} ) a = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(a ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(a ) == 0 or (len(a ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(a ) == 0 def _a ( ) -> int: a = input('''Enter sequence of brackets: ''' ) if is_balanced(a ): print(a , '''is balanced''' ) else: print(a , '''is not balanced''' ) if __name__ == "__main__": main()
0
def A_ ( _lowerCAmelCase = 50 ) -> int: UpperCamelCase : List[Any] = [[0] * 3 for _ in range(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 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
52
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): def __init__(self : Optional[int] , *__a : Optional[Any] , **__a : Dict ): warnings.warn( "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DonutImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
1
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def A_ ( _lowerCAmelCase ) -> dict[str, str]: UpperCamelCase : Optional[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key UpperCamelCase : Tuple = remove_duplicates(key.upper() ) UpperCamelCase : int = len(_lowerCAmelCase ) # First fill cipher with key characters UpperCamelCase : int = {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_lowerCAmelCase ) , 26 ): UpperCamelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase : List[str] = alphabet[i - offset] UpperCamelCase : List[Any] = char return cipher_alphabet def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: return "".join(cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( ) -> None: UpperCamelCase : int = input("Enter message to encode or decode: " ).strip() UpperCamelCase : str = input("Enter keyword: " ).strip() UpperCamelCase : Union[str, Any] = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: UpperCamelCase : List[str] = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) UpperCamelCase : str = create_cipher_map(_lowerCAmelCase ) print(func(_lowerCAmelCase , _lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
52
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from transformers import ViTConfig 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 TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any , UpperCamelCase : Tuple=13 , UpperCamelCase : Dict=30 , UpperCamelCase : int=2 , UpperCamelCase : Any=3 , UpperCamelCase : List[Any]=True , UpperCamelCase : Dict=True , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Optional[int]=2 , UpperCamelCase : str=4 , UpperCamelCase : Any=37 , UpperCamelCase : Any="gelu" , UpperCamelCase : List[Any]=0.1 , UpperCamelCase : List[Any]=0.1 , UpperCamelCase : str=10 , UpperCamelCase : Any=0.02 , UpperCamelCase : str=3 , UpperCamelCase : Optional[int]=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = is_training lowercase__ = use_labels lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase__ = (image_size // patch_size) ** 2 lowercase__ = num_patches + 1 def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ = self.get_config() return config, pixel_values, labels def UpperCamelCase__ (self : Tuple ): '''simple docstring''' return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase , initializer_range=self.initializer_range , ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' lowercase__ = TFViTModel(config=UpperCamelCase ) lowercase__ = model(UpperCamelCase , training=UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. lowercase__ = self.image_size // 2 lowercase__ = pixel_values[:, :, :image_size, :image_size] lowercase__ = model(UpperCamelCase , interpolate_pos_encoding=UpperCamelCase , training=UpperCamelCase ) lowercase__ = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase__ (self : Dict , UpperCamelCase : List[Any] , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = self.type_sequence_label_size lowercase__ = TFViTForImageClassification(UpperCamelCase ) lowercase__ = model(UpperCamelCase , labels=UpperCamelCase , training=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. lowercase__ = self.image_size // 2 lowercase__ = pixel_values[:, :, :image_size, :image_size] lowercase__ = model(UpperCamelCase , interpolate_pos_encoding=UpperCamelCase , training=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase__ = 1 lowercase__ = TFViTForImageClassification(UpperCamelCase ) lowercase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ = model(UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class __lowerCAmelCase (lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () lowerCAmelCase__ : Tuple = ( {"""feature-extraction""": TFViTModel, """image-classification""": TFViTForImageClassification} if is_tf_available() else {} ) lowerCAmelCase__ : Optional[int] = False lowerCAmelCase__ : Any = False lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = TFViTModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase , has_text_modality=UpperCamelCase , hidden_size=37 ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase__ (self : str ): '''simple docstring''' pass @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' pass def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase , tf.keras.layers.Layer ) ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase ) lowercase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ = [*signature.parameters.keys()] lowercase__ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase ) @slow def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = TFViTModel.from_pretrained('''google/vit-base-patch16-224''' ) self.assertIsNotNone(UpperCamelCase ) def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ (self : str ): '''simple docstring''' return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None @slow def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=UpperCamelCase , return_tensors='''tf''' ) # forward pass lowercase__ = model(**UpperCamelCase ) # verify the logits lowercase__ = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase ) lowercase__ = tf.constant([-0.27_44, 0.82_15, -0.08_36] ) tf.debugging.assert_near(outputs.logits[0, :3] , UpperCamelCase , atol=1E-4 )
2
from sklearn.metrics import fa_score import datasets __lowerCamelCase : List[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCamelCase : List[Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCamelCase : str = """ @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 ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def __UpperCamelCase( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ): '''simple docstring''' UpperCamelCase : List[str] = fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
52
0
'''simple docstring''' from __future__ import annotations import typing from collections import Counter def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : typing.Counter[int] = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(snake_case__ , max_perimeter + 1 ): A : Union[str, Any] = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(snake_case__ ): A : Optional[int] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCAmelCase_ ( snake_case__ = 1000 ): '''simple docstring''' A : str = pythagorean_triple(snake_case__ ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
3
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = KandinskyInpaintPipeline _UpperCAmelCase :List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] _UpperCAmelCase :Dict = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] _UpperCAmelCase :Optional[int] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _UpperCAmelCase :int = False @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCamelCase( self ): '''simple docstring''' return 100 @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : Optional[int] = MultilingualCLIP(A_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase : List[Any] = UNetaDConditionModel(**A_ ) return model @property def __UpperCamelCase( self ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.dummy_text_encoder UpperCamelCase : str = self.dummy_tokenizer UpperCamelCase : List[Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="epsilon" , thresholding=A_ , ) UpperCamelCase : Optional[Any] = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __UpperCamelCase( self , A_ , A_=0 ): '''simple docstring''' UpperCamelCase : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image UpperCamelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(A_ ) ).convert("RGB" ).resize((256, 256) ) # create mask UpperCamelCase : str = np.ones((64, 64) , dtype=np.floataa ) UpperCamelCase : str = 0 if str(A_ ).startswith("mps" ): UpperCamelCase : int = torch.manual_seed(A_ ) else: UpperCamelCase : Tuple = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase : Union[str, Any] = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = "cpu" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**A_ ) UpperCamelCase : Tuple = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase : List[Any] = output.images UpperCamelCase : List[Any] = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase : List[Any] = image[0, -3:, -3:, -1] UpperCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) UpperCamelCase : Union[str, Any] = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __UpperCamelCase( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) UpperCamelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) UpperCamelCase : Dict = np.ones((768, 768) , dtype=np.floataa ) UpperCamelCase : str = 0 UpperCamelCase : List[Any] = "a hat" UpperCamelCase : Tuple = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) UpperCamelCase : Optional[Any] = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[Any] = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() UpperCamelCase : Dict = pipeline( A_ , image=A_ , mask_image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
52
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig __snake_case =logging.get_logger(__name__) __snake_case ={ """Intel/dpt-large""": """https://huggingface.co/Intel/dpt-large/resolve/main/config.json""", # See all DPT models at https://huggingface.co/models?filter=dpt } class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : List[Any] = '''dpt''' def __init__( self : int , UpperCAmelCase__ : List[Any]=7_6_8 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : str=1_2 , UpperCAmelCase__ : List[str]=3_0_7_2 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Dict=0.0 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : List[Any]=1E-12 , UpperCAmelCase__ : List[str]=3_8_4 , UpperCAmelCase__ : int=1_6 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=[2, 5, 8, 1_1] , UpperCAmelCase__ : Union[str, Any]="project" , UpperCAmelCase__ : List[Any]=[4, 2, 1, 0.5] , UpperCAmelCase__ : List[Any]=[9_6, 1_9_2, 3_8_4, 7_6_8] , UpperCAmelCase__ : Any=2_5_6 , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Dict=0.4 , UpperCAmelCase__ : Any=2_5_5 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Dict=[1, 1_0_2_4, 2_4, 2_4] , UpperCAmelCase__ : Any=[0, 1] , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : str , ) -> int: super().__init__(**UpperCAmelCase__ ) lowerCAmelCase = hidden_size lowerCAmelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) lowerCAmelCase = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } lowerCAmelCase = BitConfig(**UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): logger.info('Initializing the config with a `BiT` backbone.' ) lowerCAmelCase = BitConfig(**UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCAmelCase = backbone_config else: raise ValueError( F'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) lowerCAmelCase = backbone_featmap_shape lowerCAmelCase = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = [] lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = qkv_bias lowerCAmelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) lowerCAmelCase = readout_type lowerCAmelCase = reassemble_factors lowerCAmelCase = neck_hidden_sizes lowerCAmelCase = fusion_hidden_size lowerCAmelCase = head_in_index lowerCAmelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) lowerCAmelCase = use_auxiliary_head lowerCAmelCase = auxiliary_loss_weight lowerCAmelCase = semantic_loss_ignore_index lowerCAmelCase = semantic_classifier_dropout def __UpperCAmelCase ( self : str ) -> Dict: lowerCAmelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: lowerCAmelCase = self.backbone_config.to_dict() lowerCAmelCase = self.__class__.model_type return output
4
class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = set_counts UpperCamelCase : int = max(A_ ) UpperCamelCase : Optional[Any] = len(A_ ) UpperCamelCase : Union[str, Any] = [1] * num_sets UpperCamelCase : Union[str, Any] = list(range(A_ ) ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = self.get_parent(A_ ) UpperCamelCase : Optional[int] = self.get_parent(A_ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] UpperCamelCase : int = 0 UpperCamelCase : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 UpperCamelCase : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] UpperCamelCase : Any = 0 UpperCamelCase : Optional[int] = src_parent UpperCamelCase : int = self.set_counts[src_parent] UpperCamelCase : Any = max(self.max_set , A_ ) return True def __UpperCamelCase( self , A_ ): '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set UpperCamelCase : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
52
0
from __future__ import annotations def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) -> None: """simple docstring""" _lowercase =len(__snake_case ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(__snake_case ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , __snake_case , __snake_case , ) def UpperCAmelCase_ ( __snake_case ) -> None: """simple docstring""" _lowercase =[] depth_first_search([] , [] , [] , __snake_case , __snake_case ) # Print all the boards for board in boards: for column in board: print(__snake_case ) print('''''' ) print(len(__snake_case ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
5
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Any = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
# Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() A : Dict = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model A : str = { # fairseq: 'wmt19-ru-en': {'length_penalty': 1.1}, 'wmt19-en-ru': {'length_penalty': 1.15}, 'wmt19-en-de': {'length_penalty': 1.0}, 'wmt19-de-en': {'length_penalty': 1.1}, # allenai: 'wmt16-en-de-dist-12-1': {'length_penalty': 0.6}, 'wmt16-en-de-dist-6-1': {'length_penalty': 0.6}, 'wmt16-en-de-12-1': {'length_penalty': 0.8}, 'wmt19-de-en-6-6-base': {'length_penalty': 0.6}, 'wmt19-de-en-6-6-big': {'length_penalty': 0.6}, } # this remaps the different models to their organization names A : Union[str, Any] = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: A : Any = 'facebook' for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: A : Dict = 'allenai' def __lowerCAmelCase ( a__ ) -> int: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} __a = dict((re.sub(R'''@@$''' , '''''' , a__ ), v) if k.endswith('''@@''' ) else (re.sub(R'''$''' , '''</w>''' , a__ ), v) for k, v in d.items() ) __a = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[F"""{k}</w>"""] __a = d[k] # restore return da def __lowerCAmelCase ( a__ , a__ ) -> Optional[int]: # prep assert os.path.exists(a__ ) os.makedirs(a__ , exist_ok=a__ ) print(F"""Writing results to {pytorch_dump_folder_path}""" ) # handle various types of models __a = basename(a__ ) __a = dirname(a__ ) __a = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel __a = cls.hub_models() __a = {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''} __a = '''.''' # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F"""using checkpoint {checkpoint_file}""" ) __a = hub_utils.from_pretrained( a__ , a__ , a__ , archive_map=a__ , **a__ ) __a = vars(chkpt['''args''']['''model'''] ) __a = args['''source_lang'''] __a = args['''target_lang'''] __a = dirname(a__ ) __a = basename(a__ ) # dicts __a = os.path.join(a__ , F"""dict.{src_lang}.txt""" ) __a = os.path.join(a__ , F"""dict.{tgt_lang}.txt""" ) __a = Dictionary.load(a__ ) __a = rewrite_dict_keys(src_dict.indices ) __a = len(a__ ) __a = os.path.join(a__ , '''vocab-src.json''' ) print(F"""Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , ensure_ascii=a__ , indent=a__ ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab __a = True for k in src_vocab.keys(): if not k.islower(): __a = False break __a = Dictionary.load(a__ ) __a = rewrite_dict_keys(tgt_dict.indices ) __a = len(a__ ) __a = os.path.join(a__ , '''vocab-tgt.json''' ) print(F"""Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , ensure_ascii=a__ , indent=a__ ) ) # merges_file (bpecodes) __a = os.path.join(a__ , VOCAB_FILES_NAMES['''merges_file'''] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" __a = os.path.join(a__ , a__ ) if os.path.exists(a__ ): break with open(a__ , encoding='''utf-8''' ) as fin: __a = fin.read() __a = re.sub(R''' \d+$''' , '''''' , a__ , 0 , re.M ) # remove frequency number print(F"""Generating {merges_file}""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as fout: fout.write(a__ ) # model config __a = os.path.join(a__ , '''config.json''' ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F"""need to extend tokenizer to support bpe={args['bpe']}""" assert args["tokenizer"] == "moses", F"""need to extend tokenizer to support bpe={args['tokenizer']}""" __a = { '''architectures''': ['''FSMTForConditionalGeneration'''], '''model_type''': '''fsmt''', '''activation_dropout''': args['''activation_dropout'''], '''activation_function''': '''relu''', '''attention_dropout''': args['''attention_dropout'''], '''d_model''': args['''decoder_embed_dim'''], '''dropout''': args['''dropout'''], '''init_std''': 0.02, '''max_position_embeddings''': args['''max_source_positions'''], '''num_hidden_layers''': args['''encoder_layers'''], '''src_vocab_size''': src_vocab_size, '''tgt_vocab_size''': tgt_vocab_size, '''langs''': [src_lang, tgt_lang], '''encoder_attention_heads''': args['''encoder_attention_heads'''], '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''], '''encoder_layerdrop''': args['''encoder_layerdrop'''], '''encoder_layers''': args['''encoder_layers'''], '''decoder_attention_heads''': args['''decoder_attention_heads'''], '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''], '''decoder_layerdrop''': args['''decoder_layerdrop'''], '''decoder_layers''': args['''decoder_layers'''], '''bos_token_id''': 0, '''pad_token_id''': 1, '''eos_token_id''': 2, '''is_encoder_decoder''': True, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_all_embeddings'''], } # good hparam defaults to start with __a = 5 __a = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: __a = best_score_hparams[model_dir]['''length_penalty'''] else: __a = 1.0 print(F"""Generating {fsmt_model_config_file}""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , ensure_ascii=a__ , indent=a__ ) ) # tokenizer config __a = os.path.join(a__ , a__ ) __a = { '''langs''': [src_lang, tgt_lang], '''model_max_length''': 1024, '''do_lower_case''': do_lower_case, } print(F"""Generating {fsmt_tokenizer_config_file}""" ) with open(a__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(a__ , ensure_ascii=a__ , indent=a__ ) ) # model __a = chkpt['''models'''][0] __a = model.state_dict() # rename keys to start with 'model.' __a = OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys __a = [ '''model.model''', '''model.encoder.version''', '''model.decoder.version''', '''model.encoder_embed_tokens.weight''', '''model.decoder_embed_tokens.weight''', '''model.encoder.embed_positions._float_tensor''', '''model.decoder.embed_positions._float_tensor''', ] for k in ignore_keys: model_state_dict.pop(a__ , a__ ) __a = FSMTConfig.from_pretrained(a__ ) __a = FSMTForConditionalGeneration(a__ ) # check that it loads ok model_new.load_state_dict(a__ , strict=a__ ) # save __a = os.path.join(a__ , a__ ) print(F"""Generating {pytorch_weights_dump_path}""" ) torch.save(a__ , a__ ) print('''Conversion is done!''' ) print('''\nLast step is to upload the files to s3''' ) print(F"""cd {data_root}""" ) print(F"""transformers-cli upload {model_dir}""" ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fsmt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) A : List[str] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
6
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class A__ ( __snake_case , __snake_case ): _UpperCAmelCase :Optional[int] = 'convnextv2' def __init__( self , A_=3 , A_=4 , A_=4 , A_=None , A_=None , A_="gelu" , A_=0.02 , A_=1e-12 , A_=0.0 , A_=224 , A_=None , A_=None , **A_ , ): '''simple docstring''' super().__init__(**A_ ) UpperCamelCase : Dict = num_channels UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Union[str, Any] = num_stages UpperCamelCase : List[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCamelCase : List[str] = [3, 3, 9, 3] if depths is None else depths UpperCamelCase : Dict = hidden_act UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : str = drop_path_rate UpperCamelCase : List[str] = image_size UpperCamelCase : List[str] = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase : str = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
52
0
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = ['image_processor', 'tokenizer'] lowerCamelCase = 'BlipImageProcessor' lowerCamelCase = 'AutoTokenizer' def __init__( self : List[Any],lowercase_ : Optional[Any],lowercase_ : List[str] )-> Optional[int]: '''simple docstring''' A__ = False super().__init__(lowercase_,lowercase_ ) A__ = self.image_processor def __call__( self : Union[str, Any],lowercase_ : ImageInput = None,lowercase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,lowercase_ : bool = True,lowercase_ : Union[bool, str, PaddingStrategy] = False,lowercase_ : Union[bool, str, TruncationStrategy] = None,lowercase_ : Optional[int] = None,lowercase_ : int = 0,lowercase_ : Optional[int] = None,lowercase_ : Optional[bool] = None,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = True,lowercase_ : Optional[Union[str, TensorType]] = None,**lowercase_ : Optional[Any],)-> BatchEncoding: '''simple docstring''' if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: A__ = self.tokenizer A__ = self.tokenizer( text=lowercase_,add_special_tokens=lowercase_,padding=lowercase_,truncation=lowercase_,max_length=lowercase_,stride=lowercase_,pad_to_multiple_of=lowercase_,return_attention_mask=lowercase_,return_overflowing_tokens=lowercase_,return_special_tokens_mask=lowercase_,return_offsets_mapping=lowercase_,return_token_type_ids=lowercase_,return_length=lowercase_,verbose=lowercase_,return_tensors=lowercase_,**lowercase_,) return text_encoding # add pixel_values A__ = self.image_processor(lowercase_,return_tensors=lowercase_ ) if text is not None: A__ = self.tokenizer( text=lowercase_,add_special_tokens=lowercase_,padding=lowercase_,truncation=lowercase_,max_length=lowercase_,stride=lowercase_,pad_to_multiple_of=lowercase_,return_attention_mask=lowercase_,return_overflowing_tokens=lowercase_,return_special_tokens_mask=lowercase_,return_offsets_mapping=lowercase_,return_token_type_ids=lowercase_,return_length=lowercase_,verbose=lowercase_,return_tensors=lowercase_,**lowercase_,) else: A__ = None if text_encoding is not None: encoding_image_processor.update(lowercase_ ) return encoding_image_processor def snake_case__ ( self : int,*lowercase_ : Any,**lowercase_ : str )-> List[str]: '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_,**lowercase_ ) def snake_case__ ( self : Optional[Any],*lowercase_ : Tuple,**lowercase_ : Optional[Any] )-> Tuple: '''simple docstring''' return self.tokenizer.decode(*lowercase_,**lowercase_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def snake_case__ ( self : List[str] )-> Optional[Any]: '''simple docstring''' A__ = self.tokenizer.model_input_names A__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
7
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_lowerCAmelCase ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def A_ ( ) -> Tuple: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def A_ ( ) -> Optional[int]: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_lowerCAmelCase ): http_head("https://huggingface.co" )
52
0
from __future__ import annotations def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Checks if the entire collection has been sorted if len(SCREAMING_SNAKE_CASE__ ) <= 1 or n <= 1: return insert_next(SCREAMING_SNAKE_CASE__ , n - 1 ) rec_insertion_sort(SCREAMING_SNAKE_CASE__ , n - 1 ) def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Checks order between adjacent elements if index >= len(SCREAMING_SNAKE_CASE__ ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order snake_case_, snake_case_ = ( collection[index], collection[index - 1], ) insert_next(SCREAMING_SNAKE_CASE__ , index + 1 ) if __name__ == "__main__": lowerCAmelCase_ = input('''Enter integers separated by spaces: ''') lowerCAmelCase_ = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
8
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') __SCREAMING_SNAKE_CASE : int = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(lowercase__ ): os.makedirs(lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.state_dict() def to_tf_var_name(lowercase__ ): for patt, repl in iter(lowercase__ ): __SCREAMING_SNAKE_CASE : Any = name.replace(lowercase__ , lowercase__ ) return F'''bert/{name}''' def create_tf_var(lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.dtypes.as_dtype(tensor.dtype ) __SCREAMING_SNAKE_CASE : int = tf.get_variable(dtype=lowercase__ , shape=tensor.shape , name=lowercase__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(lowercase__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __SCREAMING_SNAKE_CASE : Union[str, Any] = to_tf_var_name(lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __SCREAMING_SNAKE_CASE : Dict = torch_tensor.T __SCREAMING_SNAKE_CASE : Optional[Any] = create_tf_var(tensor=lowercase__ , name=lowercase__ , session=lowercase__ ) tf.keras.backend.set_value(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = session.run(lowercase__ ) print(F'''Successfully created {tf_name}: {np.allclose(lowercase__ , lowercase__ )}''' ) __SCREAMING_SNAKE_CASE : Dict = tf.train.Saver(tf.trainable_variables() ) saver.save(lowercase__ , os.path.join(lowercase__ , model_name.replace('''-''' , '''_''' ) + '''.ckpt''' ) ) def _UpperCamelCase ( lowercase__=None ): __SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser() parser.add_argument('''--model_name''' , type=lowercase__ , required=lowercase__ , help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''' , type=lowercase__ , default=lowercase__ , required=lowercase__ , help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''' , type=lowercase__ , required=lowercase__ , help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''' , type=lowercase__ , required=lowercase__ , help='''Directory in which to save tensorflow model''' ) __SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args(lowercase__ ) __SCREAMING_SNAKE_CASE : int = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=lowercase__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
9
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCamelCase : List[Any] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ __lowerCamelCase : Optional[int] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ __lowerCamelCase : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def A_ ( _lowerCAmelCase ) -> str: def remove_articles(_lowerCAmelCase ): UpperCamelCase : Tuple = re.compile(r"\b(a|an|the)\b" , re.UNICODE ) return re.sub(_lowerCAmelCase , " " , _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase ): UpperCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = [any(compute_exact(_lowerCAmelCase , _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 100 def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Optional[int] = Counter(_lowerCAmelCase ) UpperCamelCase : List[Any] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : Tuple = scount * numref UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Tuple = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Dict = ccount * numref # KEEP UpperCamelCase : List[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Union[str, Any] = keepgramcounter_rep & rgramcounter UpperCamelCase : Dict = sgramcounter_rep & rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Any = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Union[str, Any] = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : Any = sgramcounter_rep - cgramcounter_rep UpperCamelCase : str = delgramcounter_rep - rgramcounter UpperCamelCase : Any = sgramcounter_rep - rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Dict = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : str = deltmpscorea / len(_lowerCAmelCase ) # ADDITION UpperCamelCase : List[str] = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : List[str] = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) UpperCamelCase : Dict = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 UpperCamelCase : Tuple = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Tuple = addtmpscore / len(_lowerCAmelCase ) UpperCamelCase : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : List[str] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: UpperCamelCase : int = len(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = ssent.split(" " ) UpperCamelCase : Dict = csent.split(" " ) UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Any = [] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : str = [] UpperCamelCase : str = [] UpperCamelCase : Dict = [] UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = [] for rsent in rsents: UpperCamelCase : List[Any] = rsent.split(" " ) UpperCamelCase : List[str] = [] UpperCamelCase : int = [] UpperCamelCase : Tuple = [] ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : List[Any] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : List[str] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : str = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : Union[str, Any] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Union[str, Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = "13a" , _lowerCAmelCase = True ) -> Optional[Any]: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : Dict = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : str = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: UpperCamelCase : Dict = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": UpperCamelCase : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase , escape=_lowerCAmelCase ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase ) else: UpperCamelCase : Union[str, Any] = sentence if not return_str: UpperCamelCase : Tuple = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError("Sources length must match predictions and references lengths." ) UpperCamelCase : Optional[Any] = 0 for src, pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ) , normalize(_lowerCAmelCase ) , [normalize(_lowerCAmelCase ) for sent in refs] ) UpperCamelCase : Optional[int] = sari_score / len(_lowerCAmelCase ) return 100 * sari_score def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase="exp" , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> List[str]: UpperCamelCase : Optional[Any] = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] UpperCamelCase : Tuple = sacrebleu.corpus_bleu( _lowerCAmelCase , _lowerCAmelCase , smooth_method=_lowerCAmelCase , smooth_value=_lowerCAmelCase , force=_lowerCAmelCase , lowercase=_lowerCAmelCase , use_effective_order=_lowerCAmelCase , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = {} result.update({"sari": compute_sari(sources=A_ , predictions=A_ , references=A_ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A_ , references=A_ )} ) result.update({"exact": compute_em(predictions=A_ , references=A_ )} ) return result
52
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : int=7 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Union[str, Any]=19 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : Optional[Any]=5 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Union[str, Any]="gelu" , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : str=3 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : Tuple=None , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =parent lowerCamelCase__: List[str] =batch_size lowerCamelCase__: Union[str, Any] =seq_length lowerCamelCase__: List[str] =is_training lowerCamelCase__: Optional[int] =use_input_mask lowerCamelCase__: int =use_token_type_ids lowerCamelCase__: int =use_labels lowerCamelCase__: Any =vocab_size lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: Optional[Any] =num_hidden_layers lowerCamelCase__: Union[str, Any] =num_attention_heads lowerCamelCase__: Optional[Any] =intermediate_size lowerCamelCase__: int =hidden_act lowerCamelCase__: List[str] =hidden_dropout_prob lowerCamelCase__: List[Any] =attention_probs_dropout_prob lowerCamelCase__: Optional[Any] =max_position_embeddings lowerCamelCase__: str =type_vocab_size lowerCamelCase__: List[str] =type_sequence_label_size lowerCamelCase__: Dict =initializer_range lowerCamelCase__: Any =num_labels lowerCamelCase__: int =num_choices lowerCamelCase__: Tuple =scope def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int: '''simple docstring''' lowerCamelCase__: Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) lowerCamelCase__: Optional[Any] =None if self.use_input_mask: lowerCamelCase__: Tuple =random_attention_mask([self.batch_size, self.seq_length]) lowerCamelCase__: Optional[int] =None lowerCamelCase__: Optional[int] =None lowerCamelCase__: Any =None if self.use_labels: lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCamelCase__: List[str] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels) lowerCamelCase__: List[str] =ids_tensor([self.batch_size] , self.num_choices) lowerCamelCase__: Optional[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->List[str]: '''simple docstring''' lowerCamelCase__: Dict =EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=UpperCAmelCase_ , esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False} , ) return config def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: str =EsmForProteinFolding(config=UpperCAmelCase_).float() model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: str =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_) lowerCamelCase__: Optional[int] =model(UpperCAmelCase_) lowerCamelCase__: Any =model(UpperCAmelCase_) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3)) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2)) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ): Optional[Any] =config_and_inputs lowerCamelCase__: Any ={"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = False lowercase_ = (EsmForProteinFolding,) if is_torch_available() else () lowercase_ = () lowercase_ = {} if is_torch_available() else {} lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =EsmFoldModelTester(self) lowerCamelCase__: str =ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict: '''simple docstring''' lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_) @unittest.skip("Does not support attention outputs") def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any: '''simple docstring''' pass @unittest.skip def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' pass @unittest.skip("Esm does not support embedding resizing") def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' pass @unittest.skip("Esm does not support embedding resizing") def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[Any]: '''simple docstring''' pass @unittest.skip("ESMFold does not support passing input embeds!") def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' pass @unittest.skip("ESMFold does not support head pruning.") def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' pass @unittest.skip("ESMFold does not support head pruning.") def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple: '''simple docstring''' pass @unittest.skip("ESMFold does not support head pruning.") def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' pass @unittest.skip("ESMFold does not support head pruning.") def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' pass @unittest.skip("ESMFold does not support head pruning.") def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]: '''simple docstring''' pass @unittest.skip("ESMFold does not output hidden states in the normal way.") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]: '''simple docstring''' pass @unittest.skip("ESMfold does not output hidden states in the normal way.") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' pass @unittest.skip("ESMFold only has one output format.") def SCREAMING_SNAKE_CASE_ (self : Dict) ->Any: '''simple docstring''' pass @unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Any: '''simple docstring''' pass @unittest.skip("ESMFold does not support input chunking.") def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[Any]: '''simple docstring''' pass @unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments.") def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' pass @unittest.skip("ESMFold doesn't support torchscript compilation.") def SCREAMING_SNAKE_CASE_ (self : str) ->List[str]: '''simple docstring''' pass @unittest.skip("ESMFold doesn't support torchscript compilation.") def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' pass @unittest.skip("ESMFold doesn't support torchscript compilation.") def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]: '''simple docstring''' pass @unittest.skip("ESMFold doesn't support data parallel.") def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.") def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int: '''simple docstring''' pass @require_torch class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[Any] =EsmForProteinFolding.from_pretrained("facebook/esmfold_v1").float() model.eval() lowerCamelCase__: Any =torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]) lowerCamelCase__: int =model(UpperCAmelCase_)["positions"] lowerCamelCase__: Tuple =torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , UpperCAmelCase_ , atol=1E-4))
10
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : str = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = 'roberta' def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Any = type_vocab_size UpperCamelCase : int = initializer_range UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = position_embedding_type UpperCamelCase : Any = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
52
0
from __future__ import annotations def _UpperCAmelCase (UpperCamelCase__ : list ): if not nums: raise ValueError("List is empty" ) return sum(UpperCamelCase__ ) / len(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
11
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_case ): def __init__( self , A_ , A_ ): '''simple docstring''' super().__init__() self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = 100 , A_ = None , A_ = None , A_ = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCamelCase : str = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) UpperCamelCase : Union[str, Any] = int(A_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : List[str] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) UpperCamelCase : Any = int(A_ ) UpperCamelCase : Union[str, Any] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : Optional[int] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(A_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) UpperCamelCase : Optional[Any] = randn_tensor(A_ , generator=A_ , device=self.device , dtype=A_ ) # set step values self.scheduler.set_timesteps(A_ , device=audio.device ) UpperCamelCase : Optional[int] = self.scheduler.timesteps.to(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(A_ , A_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : int = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase : Optional[Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A_ )
52
0
from __future__ import annotations import bisect def lowerCamelCase__ ( A__ : list[int] , A__ : int , A__ : int = 0 , A__ : int = -1 ): '''simple docstring''' if hi < 0: __lowerCamelCase = len(A__ ) while lo < hi: __lowerCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __lowerCamelCase = mid + 1 else: __lowerCamelCase = mid return lo def lowerCamelCase__ ( A__ : list[int] , A__ : int , A__ : int = 0 , A__ : int = -1 ): '''simple docstring''' if hi < 0: __lowerCamelCase = len(A__ ) while lo < hi: __lowerCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __lowerCamelCase = mid + 1 else: __lowerCamelCase = mid return lo def lowerCamelCase__ ( A__ : list[int] , A__ : int , A__ : int = 0 , A__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(A__ , A__ , A__ , A__ ) , A__ ) def lowerCamelCase__ ( A__ : list[int] , A__ : int , A__ : int = 0 , A__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(A__ , A__ , A__ , A__ ) , A__ ) def lowerCamelCase__ ( A__ : list[int] , A__ : int ): '''simple docstring''' __lowerCamelCase = 0 __lowerCamelCase = len(A__ ) - 1 while left <= right: __lowerCamelCase = left + (right - left) // 2 __lowerCamelCase = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __lowerCamelCase = midpoint - 1 else: __lowerCamelCase = midpoint + 1 return None def lowerCamelCase__ ( A__ : list[int] , A__ : int ): '''simple docstring''' __lowerCamelCase = bisect.bisect_left(A__ , A__ ) if index != len(A__ ) and sorted_collection[index] == item: return index return None def lowerCamelCase__ ( A__ : list[int] , A__ : int , A__ : int , A__ : int ): '''simple docstring''' if right < left: return None __lowerCamelCase = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(A__ , A__ , A__ , midpoint - 1 ) else: return binary_search_by_recursion(A__ , A__ , midpoint + 1 , A__ ) if __name__ == "__main__": UpperCAmelCase_ = input('Enter numbers separated by comma:\n').strip() UpperCAmelCase_ = sorted(int(item) for item in user_input.split(',')) UpperCAmelCase_ = int(input('Enter a single number to be found in the list:\n')) UpperCAmelCase_ = binary_search(collection, target) if result is None: print(f"""{target} was not found in {collection}.""") else: print(f"""{target} was found at position {result} in {collection}.""")
12
import functools def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: UpperCamelCase : Optional[int] = len(_lowerCAmelCase ) UpperCamelCase : List[str] = len(_lowerCAmelCase ) @functools.cache def min_distance(_lowerCAmelCase , _lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa UpperCamelCase : Union[str, Any] = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _lowerCAmelCase ) , 1 + min_distance(_lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
52
0
class __lowercase : """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any]): SCREAMING_SNAKE_CASE_: List[str] = name SCREAMING_SNAKE_CASE_: Union[str, Any] = val def __str__( self : Dict): return F"{self.__class__.__name__}({self.name}, {self.val})" def __lt__( self : List[str] , lowerCAmelCase__ : Any): return self.val < other.val class __lowercase : """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: int = {} SCREAMING_SNAKE_CASE_: Any = self.build_heap(lowerCAmelCase__) def __getitem__( self : List[Any] , lowerCAmelCase__ : Dict): return self.get_value(lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Dict): return (idx - 1) // 2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : Optional[Any]): return idx * 2 + 1 def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase__ : Tuple): return idx * 2 + 2 def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase__ : Optional[int]): return self.heap_dict[key] def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Tuple = len(lowerCAmelCase__) - 1 SCREAMING_SNAKE_CASE_: List[str] = self.get_parent_idx(lowerCAmelCase__) for idx, i in enumerate(lowerCAmelCase__): SCREAMING_SNAKE_CASE_: Union[str, Any] = idx SCREAMING_SNAKE_CASE_: str = i.val for i in range(lowerCAmelCase__ , -1 , -1): self.sift_down(lowerCAmelCase__ , lowerCAmelCase__) return array def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str]): while True: SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_left_child_idx(lowerCAmelCase__) # noqa: E741 SCREAMING_SNAKE_CASE_: Dict = self.get_right_child_idx(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = idx if l < len(lowerCAmelCase__) and array[l] < array[idx]: SCREAMING_SNAKE_CASE_: List[str] = l if r < len(lowerCAmelCase__) and array[r] < array[smallest]: SCREAMING_SNAKE_CASE_: str = r if smallest != idx: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any = array[smallest], array[idx] ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ): Optional[Any] = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) SCREAMING_SNAKE_CASE_: Optional[int] = smallest else: break def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : str): SCREAMING_SNAKE_CASE_: Any = self.get_parent_idx(lowerCAmelCase__) while p >= 0 and self.heap[p] > self.heap[idx]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = self.heap[idx], self.heap[p] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) SCREAMING_SNAKE_CASE_: Union[str, Any] = p SCREAMING_SNAKE_CASE_: Optional[int] = self.get_parent_idx(lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any]): return self.heap[0] def _SCREAMING_SNAKE_CASE ( self : Dict): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple = self.heap[-1], self.heap[0] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) SCREAMING_SNAKE_CASE_: int = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap) return x def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : Tuple): self.heap.append(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = len(self.heap) - 1 SCREAMING_SNAKE_CASE_: List[str] = node.val self.sift_up(len(self.heap) - 1) def _SCREAMING_SNAKE_CASE ( self : List[Any]): return len(self.heap) == 0 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int]): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" SCREAMING_SNAKE_CASE_: Any = new_value SCREAMING_SNAKE_CASE_: Tuple = new_value self.sift_up(self.idx_of_element[node]) lowerCAmelCase : int = Node("""R""", -1) lowerCAmelCase : str = Node("""B""", 6) lowerCAmelCase : str = Node("""A""", 3) lowerCAmelCase : List[str] = Node("""X""", 1) lowerCAmelCase : Union[str, Any] = Node("""E""", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array lowerCAmelCase : Optional[Any] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("""Min Heap - before decrease key""") for i in my_min_heap.heap: print(i) print("""Min Heap - After decrease key of node [B -> -17]""") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
13
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __lowerCamelCase : str = random.Random() if is_torch_available(): import torch def A_ ( _lowerCAmelCase , _lowerCAmelCase=1.0 , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: if rng is None: UpperCamelCase : Optional[int] = global_rng UpperCamelCase : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class A__ ( unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ): '''simple docstring''' UpperCamelCase : Tuple = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Union[str, Any] = feature_size UpperCamelCase : List[str] = padding_value UpperCamelCase : Optional[Any] = sampling_rate UpperCamelCase : List[str] = return_attention_mask UpperCamelCase : List[Any] = do_normalize def __UpperCamelCase( self ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCamelCase( self , A_=False , A_=False ): '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: UpperCamelCase : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Dict = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Union[str, Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = ASTFeatureExtractor def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = ASTFeatureExtractionTester(self ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Dict = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCamelCase : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(A_ ) UpperCamelCase : Any = feat_extract(A_ , return_tensors="np" ).input_values UpperCamelCase : List[str] = feat_extract(A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) @require_torch def __UpperCamelCase( self ): '''simple docstring''' import torch UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : str = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __UpperCamelCase( self , A_ ): '''simple docstring''' from datasets import load_dataset UpperCamelCase : Dict = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech UpperCamelCase : Any = ds.sort("id" ).select(range(A_ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : Tuple = ASTFeatureExtractor() UpperCamelCase : str = feature_extractor(A_ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A_ , atol=1e-4 ) )
52
0
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { """deepmind/language-perceiver""": """https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json""", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''perceiver''' def __init__( self : Any , UpperCAmelCase__ : Optional[Any]=256 , UpperCAmelCase__ : Any=1_280 , UpperCAmelCase__ : int=768 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[Any]=26 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : int=8 , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : str="kv" , UpperCAmelCase__ : Tuple=1 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : str=1e-12 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Any=262 , UpperCAmelCase__ : str=2_048 , UpperCAmelCase__ : Any=56 , UpperCAmelCase__ : Dict=[368, 496] , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : List[Any]=1_920 , UpperCAmelCase__ : List[Any]=16 , UpperCAmelCase__ : Optional[Any]=[1, 16, 224, 224] , **UpperCAmelCase__ : Dict , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase__) A__ = num_latents A__ = d_latents A__ = d_model A__ = num_blocks A__ = num_self_attends_per_block A__ = num_self_attention_heads A__ = num_cross_attention_heads A__ = qk_channels A__ = v_channels A__ = cross_attention_shape_for_attention A__ = self_attention_widening_factor A__ = cross_attention_widening_factor A__ = hidden_act A__ = attention_probs_dropout_prob A__ = initializer_range A__ = layer_norm_eps A__ = use_query_residual # masked language modeling attributes A__ = vocab_size A__ = max_position_embeddings # image classification attributes A__ = image_size # flow attributes A__ = train_size # multimodal autoencoding attributes A__ = num_frames A__ = audio_samples_per_frame A__ = samples_per_patch A__ = output_shape class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''inputs''', dynamic_axis), ('''attention_mask''', dynamic_axis), ]) @property def SCREAMING_SNAKE_CASE ( self : str) ->float: '''simple docstring''' return 1e-4 def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[TensorType] = None , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 40 , UpperCAmelCase__ : int = 40 , ) ->Mapping[str, Any]: '''simple docstring''' if isinstance(UpperCAmelCase__ , UpperCAmelCase__): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX A__ = compute_effective_axis_dimension( UpperCAmelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX A__ = preprocessor.num_special_tokens_to_add(UpperCAmelCase__) A__ = compute_effective_axis_dimension( UpperCAmelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCAmelCase__) # Generate dummy inputs according to compute batch and sequence A__ = [''' '''.join(['''a''']) * seq_length] * batch_size A__ = dict(preprocessor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__)) A__ = inputs.pop('''input_ids''') return inputs elif isinstance(UpperCAmelCase__ , UpperCAmelCase__) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX A__ = compute_effective_axis_dimension(UpperCAmelCase__ , fixed_dimension=OnnxConfig.default_fixed_batch) A__ = self._generate_dummy_images(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) A__ = dict(preprocessor(images=UpperCAmelCase__ , return_tensors=UpperCAmelCase__)) A__ = inputs.pop('''pixel_values''') return inputs else: raise ValueError( '''Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.''')
14
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ): '''simple docstring''' UpperCamelCase : int = bp_numa UpperCamelCase : int = bp_numa UpperCamelCase : List[Any] = bp_numa UpperCamelCase : Optional[int] = conva_get[:2] UpperCamelCase : Optional[Any] = conva_get[2] UpperCamelCase : Dict = size_pa UpperCamelCase : Union[str, Any] = rate_w UpperCamelCase : Dict = rate_t UpperCamelCase : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] UpperCamelCase : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : Optional[Any] = -2 * np.random.rand(self.conva[1] ) + 1 UpperCamelCase : Any = -2 * np.random.rand(self.num_bpa ) + 1 UpperCamelCase : int = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(A_ , "wb" ) as f: pickle.dump(A_ , A_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __UpperCamelCase( cls , A_ ): '''simple docstring''' with open(A_ , "rb" ) as f: UpperCamelCase : Optional[Any] = pickle.load(A_ ) # noqa: S301 UpperCamelCase : List[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) UpperCamelCase : Union[str, Any] = model_dic.get("size_pooling1" ) UpperCamelCase : List[Any] = model_dic.get("num_bp1" ) UpperCamelCase : Dict = model_dic.get("num_bp2" ) UpperCamelCase : Dict = model_dic.get("num_bp3" ) UpperCamelCase : Dict = model_dic.get("rate_weight" ) UpperCamelCase : str = model_dic.get("rate_thre" ) # create model instance UpperCamelCase : Any = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter UpperCamelCase : str = model_dic.get("w_conv1" ) UpperCamelCase : Optional[Any] = model_dic.get("wkj" ) UpperCamelCase : int = model_dic.get("vji" ) UpperCamelCase : Any = model_dic.get("thre_conv1" ) UpperCamelCase : Optional[int] = model_dic.get("thre_bp2" ) UpperCamelCase : Union[str, Any] = model_dic.get("thre_bp3" ) return conv_ins def __UpperCamelCase( self , A_ ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def __UpperCamelCase( self , A_ ): '''simple docstring''' return round(A_ , 3 ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = convs[0] UpperCamelCase : Optional[Any] = convs[1] UpperCamelCase : Optional[Any] = np.shape(A_ )[0] # get the data slice of original image data, data_focus UpperCamelCase : List[str] = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): UpperCamelCase : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): UpperCamelCase : str = [] for i_focus in range(len(A_ ) ): UpperCamelCase : List[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) UpperCamelCase : Optional[int] = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion UpperCamelCase : List[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) UpperCamelCase : Tuple = np.asarray(A_ ) return focus_list, data_featuremap def __UpperCamelCase( self , A_ , A_ , A_="average_pool" ): '''simple docstring''' UpperCamelCase : Any = len(featuremaps[0] ) UpperCamelCase : str = int(size_map / size_pooling ) UpperCamelCase : Optional[int] = [] for i_map in range(len(A_ ) ): UpperCamelCase : Tuple = featuremaps[i_map] UpperCamelCase : Any = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): UpperCamelCase : int = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) UpperCamelCase : Optional[Any] = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = [] for i in range(len(A_ ) ): UpperCamelCase : List[Any] = np.shape(data[i] ) UpperCamelCase : str = data[i].reshape(1 , shapes[0] * shapes[1] ) UpperCamelCase : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) UpperCamelCase : Any = np.asarray(A_ ) return data_expanded def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = np.asarray(A_ ) UpperCamelCase : List[Any] = np.shape(A_ ) UpperCamelCase : Any = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[int] = 0 for i_map in range(A_ ): UpperCamelCase : int = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): UpperCamelCase : str = pd_pool[ i_pool ] UpperCamelCase : str = i_pool + 1 UpperCamelCase : str = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=bool ): '''simple docstring''' print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(A_ )) ) print((" - - Shape: Teach_Data ", np.shape(A_ )) ) UpperCamelCase : List[str] = 0 UpperCamelCase : Union[str, Any] = [] UpperCamelCase : int = 1_0000 while rp < n_repeat and mse >= error_accuracy: UpperCamelCase : Tuple = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) UpperCamelCase : Any = np.asmatrix(datas_train[p] ) UpperCamelCase : List[str] = np.asarray(datas_teach[p] ) UpperCamelCase , UpperCamelCase : Dict = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : Tuple = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : int = np.shape(A_ ) UpperCamelCase : List[str] = self._expand(A_ ) UpperCamelCase : Optional[int] = data_bp_input UpperCamelCase : str = np.dot(A_ , self.vji.T ) - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) UpperCamelCase : List[Any] = np.dot(A_ , self.wkj.T ) - self.thre_bpa UpperCamelCase : Dict = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- UpperCamelCase : List[Any] = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : str = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : Any = np.dot(A_ , self.vji ) UpperCamelCase : Dict = pd_i_all / (self.size_poolinga * self.size_poolinga) UpperCamelCase : List[Any] = pd_conva_pooled.T.getA().tolist() UpperCamelCase : List[Any] = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): UpperCamelCase : List[Any] = self._expand_mat(pd_conva_all[k_conv] ) UpperCamelCase : List[Any] = self.rate_weight * np.dot(A_ , A_ ) UpperCamelCase : str = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) UpperCamelCase : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer UpperCamelCase : Optional[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight UpperCamelCase : List[Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight UpperCamelCase : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre UpperCamelCase : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image UpperCamelCase : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) UpperCamelCase : Any = rp + 1 UpperCamelCase : Union[str, Any] = error_count / patterns all_mse.append(A_ ) def draw_error(): UpperCamelCase : Tuple = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , "+-" ) plt.plot(A_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(A_ )) ) for p in range(len(A_ ) ): UpperCamelCase : int = np.asmatrix(datas_test[p] ) UpperCamelCase , UpperCamelCase : Any = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : List[str] = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : Dict = self._expand(A_ ) UpperCamelCase : List[Any] = data_bp_input UpperCamelCase : Any = bp_outa * self.vji.T - self.thre_bpa UpperCamelCase : List[Any] = self.sig(A_ ) UpperCamelCase : int = bp_outa * self.wkj.T - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) UpperCamelCase : List[str] = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = np.asmatrix(A_ ) UpperCamelCase , UpperCamelCase : List[Any] = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : str = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
52
0
def UpperCAmelCase ( a_ ) -> float: """simple docstring""" __A = 0 while len(a_ ) > 1: __A = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): __A = files.index(min(a_ ) ) temp += files[min_index] files.pop(a_ ) files.append(a_ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
15
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Any = { """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""", # See all BART models at https://huggingface.co/models?filter=bart } class A__ ( __snake_case ): _UpperCAmelCase :Dict = 'bart' _UpperCAmelCase :str = ['past_key_values'] _UpperCAmelCase :Any = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , A_=5_0265 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=3 , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , **A_ , ): '''simple docstring''' UpperCamelCase : int = vocab_size UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Any = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = encoder_attention_heads UpperCamelCase : Optional[int] = decoder_ffn_dim UpperCamelCase : List[str] = decoder_layers UpperCamelCase : Optional[int] = decoder_attention_heads UpperCamelCase : int = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Tuple = activation_dropout UpperCamelCase : Tuple = activation_function UpperCamelCase : int = init_std UpperCamelCase : List[Any] = encoder_layerdrop UpperCamelCase : List[str] = decoder_layerdrop UpperCamelCase : Dict = classifier_dropout UpperCamelCase : Optional[int] = use_cache UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , A_ ): UpperCamelCase : 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." ) class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase : List[str] = {0: "batch"} UpperCamelCase : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase : Dict = {0: "batch", 1: "decoder_sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(A_ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase : Any = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase , UpperCamelCase : Optional[int] = self.num_layers for i in range(A_ ): UpperCamelCase : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase : Optional[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Tuple = super().outputs else: UpperCamelCase : Dict = super(A_ , self ).outputs if self.use_past: UpperCamelCase , UpperCamelCase : int = self.num_layers for i in range(A_ ): UpperCamelCase : int = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Tuple = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) # Generate decoder inputs UpperCamelCase : List[Any] = seq_length if not self.use_past else 1 UpperCamelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) UpperCamelCase : Optional[int] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase : List[Any] = dict(**A_ , **A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Optional[Any] = common_inputs["input_ids"].shape UpperCamelCase : List[Any] = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase , UpperCamelCase : List[str] = self.num_attention_heads UpperCamelCase : int = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : List[Any] = decoder_seq_length + 3 UpperCamelCase : str = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase : int = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(A_ , A_ )] , dim=1 ) UpperCamelCase : int = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase , UpperCamelCase : Union[str, Any] = self.num_layers UpperCamelCase : Any = min(A_ , A_ ) UpperCamelCase : List[str] = max(A_ , A_ ) - min_num_layers UpperCamelCase : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(A_ ): common_inputs["past_key_values"].append( ( torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), ) ) # TODO: test this. UpperCamelCase : Optional[Any] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(A_ , A_ ): common_inputs["past_key_values"].append((torch.zeros(A_ ), torch.zeros(A_ )) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : int = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Union[str, Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase : Optional[Any] = seqlen + 2 UpperCamelCase , UpperCamelCase : List[Any] = self.num_layers UpperCamelCase , UpperCamelCase : Optional[int] = self.num_attention_heads UpperCamelCase : str = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : Optional[Any] = common_inputs["attention_mask"].dtype UpperCamelCase : int = torch.cat( [common_inputs["attention_mask"], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) UpperCamelCase : Optional[Any] = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(A_ ) ] return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase : Union[str, Any] = tokenizer.num_special_tokens_to_add(A_ ) UpperCamelCase : int = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase : int = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase : Dict = dict(tokenizer(A_ , return_tensors=A_ ) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) elif self.task == "causal-lm": UpperCamelCase : List[str] = self._generate_dummy_inputs_for_causal_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) else: UpperCamelCase : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) return common_inputs def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[Any] = super()._flatten_past_key_values_(A_ , A_ , A_ , A_ ) else: UpperCamelCase : Optional[Any] = super(A_ , self )._flatten_past_key_values_( A_ , A_ , A_ , A_ )
52
0
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30_522, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('Counting occurrences for MLM.') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
16
from math import sqrt def A_ ( _lowerCAmelCase ) -> bool: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" UpperCamelCase : List[Any] = True # 0 and 1 are none primes. if number <= 1: UpperCamelCase : List[Any] = False for divisor in range(2 , int(round(sqrt(_lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCamelCase : Union[str, Any] = False break # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'status' must been from type bool" return status def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCamelCase : int = list(range(2 , n + 1 ) ) UpperCamelCase : Optional[int] = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_lowerCAmelCase ) ): for j in range(i + 1 , len(_lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCamelCase : Tuple = 0 # filters actual prime numbers. UpperCamelCase : str = [x for x in begin_list if x != 0] # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" UpperCamelCase : str = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(_lowerCAmelCase ): ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" UpperCamelCase : Optional[Any] = [] # this list will be returns of the function. # potential prime number factors. UpperCamelCase : Tuple = 2 UpperCamelCase : str = number if number == 0 or number == 1: ans.append(_lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_lowerCAmelCase ): while quotient != 1: if is_prime(_lowerCAmelCase ) and (quotient % factor == 0): ans.append(_lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Any = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = max(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Union[str, Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Dict = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = min(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def A_ ( _lowerCAmelCase ) -> List[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def A_ ( _lowerCAmelCase ) -> Any: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (number > 2) and is_even(_lowerCAmelCase ) ), "'number' must been an int, even and > 2" UpperCamelCase : List[str] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCamelCase : Dict = get_prime_numbers(_lowerCAmelCase ) UpperCamelCase : Tuple = len(_lowerCAmelCase ) # run variable for while-loops. UpperCamelCase : Optional[int] = 0 UpperCamelCase : int = None # exit variable. for break up the loops UpperCamelCase : Union[str, Any] = True while i < len_pn and loop: UpperCamelCase : Tuple = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCamelCase : Any = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (len(_lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Tuple = 0 while numbera != 0: UpperCamelCase : Tuple = numbera % numbera UpperCamelCase : Any = numbera UpperCamelCase : Union[str, Any] = rest # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Optional[int] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCamelCase : List[Any] = prime_factorization(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = prime_factorization(_lowerCAmelCase ) elif numbera == 1 or numbera == 1: UpperCamelCase : Optional[Any] = [] UpperCamelCase : int = [] UpperCamelCase : List[Any] = max(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 UpperCamelCase : List[str] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) UpperCamelCase : Tuple = prime_fac_a.count(_lowerCAmelCase ) for _ in range(max(_lowerCAmelCase , _lowerCAmelCase ) ): ans *= n else: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCamelCase : Any = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" UpperCamelCase : int = 0 UpperCamelCase : int = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_lowerCAmelCase ): ans += 1 # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and is_prime( _lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( is_prime(_lowerCAmelCase ) and is_prime(_lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCamelCase : str = p_number_a + 1 # jump to the next number UpperCamelCase : Dict = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(_lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ans[0] != p_number_a and ans[len(_lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def A_ ( _lowerCAmelCase ) -> List[str]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" UpperCamelCase : Dict = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(_lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def A_ ( _lowerCAmelCase ) -> int: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCamelCase : int = get_divisors(_lowerCAmelCase ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(_lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCamelCase : List[str] = gcd(abs(_lowerCAmelCase ) , abs(_lowerCAmelCase ) ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def A_ ( _lowerCAmelCase ) -> Dict: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" UpperCamelCase : str = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" UpperCamelCase : Dict = 0 UpperCamelCase : Dict = 1 UpperCamelCase : Union[str, Any] = 1 # this will be return for _ in range(n - 1 ): UpperCamelCase : Any = ans ans += fiba UpperCamelCase : str = tmp return ans
52
0
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class _lowerCAmelCase : """simple docstring""" def __init__( self : Any, UpperCAmelCase__ : List[Any], ): __lowercase = parent __lowercase = 1_3 __lowercase = 7 __lowercase = 3_0 __lowercase = self.seq_length + self.mem_len __lowercase = 1_5 __lowercase = True __lowercase = True __lowercase = 9_9 __lowercase = [1_0, 5_0, 8_0] __lowercase = 3_2 __lowercase = 3_2 __lowercase = 4 __lowercase = 8 __lowercase = 1_2_8 __lowercase = 2 __lowercase = 2 __lowercase = None __lowercase = 1 __lowercase = 0 __lowercase = 3 __lowercase = self.vocab_size - 1 __lowercase = 0.01 def _lowercase ( self : List[str] ): __lowercase = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __lowercase = TransfoXLConfig( vocab_size=self.vocab_size, mem_len=self.mem_len, clamp_len=self.clamp_len, cutoffs=self.cutoffs, d_model=self.hidden_size, d_embed=self.d_embed, n_head=self.num_attention_heads, d_head=self.d_head, d_inner=self.d_inner, div_val=self.div_val, n_layer=self.num_hidden_layers, eos_token_id=self.eos_token_id, pad_token_id=self.vocab_size - 1, init_range=self.init_range, num_labels=self.num_labels, ) return (config, input_ids_a, input_ids_a, lm_labels) def _lowercase ( self : List[Any] ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def _lowercase ( self : int, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : int, UpperCAmelCase__ : Tuple ): __lowercase = TFTransfoXLModel(UpperCAmelCase__ ) __lowercase ,__lowercase = model(UpperCAmelCase__ ).to_tuple() __lowercase = {"input_ids": input_ids_a, "mems": mems_a} __lowercase ,__lowercase = model(UpperCAmelCase__ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a], [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, ) self.parent.assertListEqual( [mem.shape for mem in mems_a], [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, ) def _lowercase ( self : List[str], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Dict, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : List[str] ): __lowercase = TFTransfoXLLMHeadModel(UpperCAmelCase__ ) __lowercase ,__lowercase = model(UpperCAmelCase__ ).to_tuple() __lowercase = {"input_ids": input_ids_a, "labels": lm_labels} __lowercase ,__lowercase = model(UpperCAmelCase__ ).to_tuple() __lowercase ,__lowercase = model([input_ids_a, mems_a] ).to_tuple() __lowercase = {"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels} __lowercase ,__lowercase = model(UpperCAmelCase__ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape, (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a], [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, ) self.parent.assertEqual(lm_logits_a.shape, (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a], [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, ) def _lowercase ( self : Optional[Any], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : str, UpperCAmelCase__ : str, UpperCAmelCase__ : Optional[int] ): __lowercase = TFTransfoXLForSequenceClassification(UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def _lowercase ( self : Any ): __lowercase = self.prepare_config_and_inputs() ((__lowercase) ,(__lowercase) ,(__lowercase) ,(__lowercase)) = config_and_inputs __lowercase = {"input_ids": input_ids_a} return config, inputs_dict @require_tf class _lowerCAmelCase ( lowercase ,lowercase ,unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __UpperCAmelCase : Union[str, Any] = () if is_tf_available() else () __UpperCAmelCase : List[str] = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False def _lowercase ( self : str, UpperCAmelCase__ : List[str], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Any, UpperCAmelCase__ : Tuple, UpperCAmelCase__ : int ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def _lowercase ( self : List[str] ): __lowercase = TFTransfoXLModelTester(self ) __lowercase = ConfigTester(self, config_class=UpperCAmelCase__, d_embed=3_7 ) def _lowercase ( self : int ): self.config_tester.run_common_tests() def _lowercase ( self : Union[str, Any] ): self.model_tester.set_seed() __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*UpperCAmelCase__ ) def _lowercase ( self : Tuple ): self.model_tester.set_seed() __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCAmelCase__ ) def _lowercase ( self : Optional[int] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCAmelCase__ ) def _lowercase ( self : int ): __lowercase ,__lowercase = self.model_tester.prepare_config_and_inputs_for_common() __lowercase = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __lowercase = model_class(UpperCAmelCase__ ) assert isinstance(model.get_input_embeddings(), tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __lowercase = model.get_output_embeddings() assert isinstance(UpperCAmelCase__, tf.keras.layers.Layer ) __lowercase = model.get_bias() assert name is None else: __lowercase = model.get_output_embeddings() assert x is None __lowercase = model.get_bias() assert name is None def _lowercase ( self : List[str] ): # TODO JP: Make TransfoXL XLA compliant pass @slow def _lowercase ( self : Tuple ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = TFTransfoXLModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def _lowercase ( self : Any ): pass @require_tf class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @unittest.skip("Skip test until #12651 is resolved." ) @slow def _lowercase ( self : List[str] ): __lowercase = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off __lowercase = tf.convert_to_tensor([[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0]], dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off __lowercase = [3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0,3_3,1,1_8_5_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_8,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __lowercase = model.generate(UpperCAmelCase__, max_length=2_0_0, do_sample=UpperCAmelCase__ ) self.assertListEqual(output_ids[0].numpy().tolist(), UpperCAmelCase__ )
17
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 : str = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCamelCase : Tuple = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCamelCase : List[str] = 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 : Optional[Any] = re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") __lowerCamelCase : List[str] = { """DecisionTransformerConfig""", """EncoderDecoderConfig""", """MusicgenConfig""", """RagConfig""", """SpeechEncoderDecoderConfig""", """TimmBackboneConfig""", """VisionEncoderDecoderConfig""", """VisionTextDualEncoderConfig""", """LlamaConfig""", } def A_ ( _lowerCAmelCase ) -> List[str]: UpperCamelCase : Optional[Any] = None # source code of `config_class` UpperCamelCase : Tuple = inspect.getsource(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = _re_checkpoint.findall(_lowerCAmelCase ) # 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 : Dict = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase : Any = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: UpperCamelCase : List[Any] = ckpt_name break return checkpoint def A_ ( ) -> List[str]: UpperCamelCase : Optional[int] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCamelCase : Union[str, Any] = get_checkpoint_from_config_class(_lowerCAmelCase ) UpperCamelCase : Optional[int] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Any = "\n".join(sorted(_lowerCAmelCase ) ) raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
52
0
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput __lowerCamelCase : Optional[int] = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( A__ ): def __init__( self : Optional[int],*_A : Tuple,_A : List[Any]=None,_A : Tuple=None,_A : Optional[int]=None,**_A : Union[str, Any] ): """simple docstring""" super().__init__(*_A,**_A ) SCREAMING_SNAKE_CASE_ : Tuple = eval_examples SCREAMING_SNAKE_CASE_ : str = post_process_function SCREAMING_SNAKE_CASE_ : Dict = quant_trainer_args SCREAMING_SNAKE_CASE_ : Optional[int] = 128 # default number of calibration samples def __UpperCamelCase ( self : Optional[int],_A : Optional[Any]=None ): """simple docstring""" if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE_ : Optional[Any] = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = self._remove_unused_columns(_A,description="Calibration" ) return DataLoader( _A,batch_size=self.args.eval_batch_size,collate_fn=self.data_collator,drop_last=self.args.dataloader_drop_last,num_workers=self.args.dataloader_num_workers,pin_memory=self.args.dataloader_pin_memory,shuffle=_A,) def __UpperCamelCase ( self : List[Any],_A : Optional[Any]=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE_ : Dict = self.get_calib_dataloader(_A ) SCREAMING_SNAKE_CASE_ : List[Any] = self.model quant_trainer.configure_model(_A,self.quant_trainer_args,calib=_A ) model.eval() quant_trainer.enable_calibration(_A ) logger.info("***** Running calibration *****" ) logger.info(F' Num examples = {self.calib_num}' ) logger.info(F' Batch size = {calib_dataloader.batch_size}' ) for step, inputs in enumerate(_A ): # Prediction step SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.prediction_step(_A,_A,prediction_loss_only=_A ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(_A,self.quant_trainer_args ) SCREAMING_SNAKE_CASE_ : Any = model def __UpperCamelCase ( self : Optional[Any],_A : Dict=None,_A : List[str]=None,_A : Union[str, Any]=None,_A : str = "eval" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE_ : Any = self.get_eval_dataloader(_A ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : List[str] = self.compute_metrics SCREAMING_SNAKE_CASE_ : List[Any] = None SCREAMING_SNAKE_CASE_ : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE_ : str = eval_loop( _A,description="Evaluation",prediction_loss_only=True if compute_metrics is None else None,ignore_keys=_A,) finally: SCREAMING_SNAKE_CASE_ : List[Any] = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE_ : Any = self.post_process_function(_A,_A,output.predictions ) SCREAMING_SNAKE_CASE_ : Any = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): SCREAMING_SNAKE_CASE_ : str = metrics.pop(_A ) self.log(_A ) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE_ : List[Any] = self.callback_handler.on_evaluate(self.args,self.state,self.control,_A ) return metrics def __UpperCamelCase ( self : Any,_A : Optional[Any],_A : List[Any],_A : str=None,_A : str = "test" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : Dict = self.compute_metrics SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE_ : Any = eval_loop( _A,description="Prediction",prediction_loss_only=True if compute_metrics is None else None,ignore_keys=_A,) finally: SCREAMING_SNAKE_CASE_ : List[str] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE_ : List[str] = self.post_process_function(_A,_A,output.predictions,"predict" ) SCREAMING_SNAKE_CASE_ : int = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = metrics.pop(_A ) return PredictionOutput(predictions=predictions.predictions,label_ids=predictions.label_ids,metrics=_A ) def __UpperCamelCase ( self : Optional[int],_A : Any="./" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.eval_dataset SCREAMING_SNAKE_CASE_ : List[Any] = self.get_eval_dataloader(_A ) SCREAMING_SNAKE_CASE_ : int = next(iter(_A ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE_ : List[Any] = tuple(v.to(_A ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE_ : Dict = True SCREAMING_SNAKE_CASE_ : int = self.model.to(_A ) model.eval() model.float() SCREAMING_SNAKE_CASE_ : Any = model.module if hasattr(_A,"module" ) else model quant_trainer.configure_model(_A,self.quant_trainer_args ) SCREAMING_SNAKE_CASE_ : int = os.path.join(_A,"model.onnx" ) logger.info(F'exporting model to {output_model_file}' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {0: "batch_size", 1: "seq_len"} torch.onnx.export( _A,_A,_A,export_params=_A,opset_version=13,do_constant_folding=_A,input_names=["input_ids", "attention_mask", "token_type_ids"],output_names=["output_start_logits", "output_end_logits"],dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, },verbose=_A,) logger.info("onnx export finished" )
18
from __future__ import annotations from functools import lru_cache from math import ceil __lowerCamelCase : str = 100 __lowerCamelCase : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __lowerCamelCase : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def A_ ( _lowerCAmelCase ) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} UpperCamelCase : set[int] = set() UpperCamelCase : int UpperCamelCase : int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A_ ( _lowerCAmelCase = 5000 ) -> int | None: for number_to_partition in range(1 , _lowerCAmelCase ): if len(partition(_lowerCAmelCase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
52
0
def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): return int((input_a, input_a).count(0 ) == 0 ) def lowerCamelCase_ ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
19
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Optional[int] = int(_lowerCAmelCase ) if decimal in (0, 1): # Exit cases for the recursion return str(_lowerCAmelCase ) UpperCamelCase , UpperCamelCase : Dict = divmod(_lowerCAmelCase , 2 ) return binary_recursive(_lowerCAmelCase ) + str(_lowerCAmelCase ) def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = str(_lowerCAmelCase ).strip() if not number: raise ValueError("No input value was provided" ) UpperCamelCase : Optional[int] = "-" if number.startswith("-" ) else "" UpperCamelCase : Any = number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return F"""{negative}0b{binary_recursive(int(_lowerCAmelCase ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
52
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase : Dict = logging.get_logger(__name__) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ) -> Any: lowercase : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"deit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"deit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"deit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"deit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"deit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"deit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"deit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"deit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"deit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"deit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" lowercase : Any = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: lowercase : Any = """""" else: lowercase : Dict = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase : Tuple = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) lowercase : Dict = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict lowercase : Dict = in_proj_weight[ : config.hidden_size, : ] lowercase : Optional[Any] = in_proj_bias[: config.hidden_size] lowercase : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase : str = in_proj_weight[ -config.hidden_size :, : ] lowercase : Optional[int] = in_proj_bias[-config.hidden_size :] def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: lowercase : List[Any] = dct.pop(SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = val def _snake_case( ) -> str: lowercase : List[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowercase : str = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: lowercase : Tuple = DeiTConfig() # all deit models have fine-tuned heads lowercase : int = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size lowercase : Optional[Any] = 1_000 lowercase : Any = """huggingface/label-files""" lowercase : List[str] = """imagenet-1k-id2label.json""" lowercase : Optional[Any] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type="""dataset""" ) , """r""" ) ) lowercase : Tuple = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} lowercase : Any = idalabel lowercase : str = {v: k for k, v in idalabel.items()} lowercase : List[Any] = int(deit_name[-6:-4] ) lowercase : Optional[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): lowercase : Union[str, Any] = 192 lowercase : List[Any] = 768 lowercase : List[Any] = 12 lowercase : Union[str, Any] = 3 elif deit_name[9:].startswith("""small""" ): lowercase : Optional[int] = 384 lowercase : str = 1_536 lowercase : Optional[int] = 12 lowercase : Tuple = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): lowercase : List[str] = 1_024 lowercase : List[str] = 4_096 lowercase : List[str] = 24 lowercase : List[str] = 16 # load original model from timm lowercase : List[str] = timm.create_model(SCREAMING_SNAKE_CASE__ , pretrained=SCREAMING_SNAKE_CASE__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowercase : Optional[int] = timm_model.state_dict() lowercase : List[Any] = create_rename_keys(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) read_in_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load HuggingFace model lowercase : Tuple = DeiTForImageClassificationWithTeacher(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # Check outputs on an image, prepared by DeiTImageProcessor lowercase : Optional[int] = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 lowercase : Optional[Any] = DeiTImageProcessor(size=SCREAMING_SNAKE_CASE__ , crop_size=config.image_size ) lowercase : List[str] = image_processor(images=prepare_img() , return_tensors="""pt""" ) lowercase : int = encoding["""pixel_values"""] lowercase : List[Any] = model(SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = timm_model(SCREAMING_SNAKE_CASE__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE__ , outputs.logits , atol=1e-3 ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(f"Saving model {deit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--deit_name""", default="""vit_deit_base_distilled_patch16_224""", type=str, help="""Name of the DeiT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowercase : Optional[Any] = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
20
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=24 , A_=2 , A_=6 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=None , A_=1000 , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : Dict = seq_length UpperCamelCase : Tuple = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : Optional[Any] = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : Optional[int] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : Optional[int] = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Optional[int] = scope UpperCamelCase : int = range_bbox def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase : Union[str, Any] = bbox[i, j, 3] UpperCamelCase : int = bbox[i, j, 1] UpperCamelCase : int = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : List[str] = bbox[i, j, 2] UpperCamelCase : Optional[int] = bbox[i, j, 0] UpperCamelCase : Optional[Any] = t UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : str = None if self.use_token_type_ids: UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Dict = None UpperCamelCase : int = None if self.use_labels: UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCamelCase( self ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = LiltModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = model(A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ ) UpperCamelCase : Optional[int] = model(A_ , bbox=A_ , token_type_ids=A_ ) UpperCamelCase : Any = model(A_ , bbox=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = self.num_labels UpperCamelCase : Dict = LiltForTokenClassification(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Dict = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Dict = LiltForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Tuple = config_and_inputs UpperCamelCase : Tuple = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) _UpperCAmelCase :Dict = False _UpperCAmelCase :Union[str, Any] = False def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' return True def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = LiltModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = LiltModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @slow class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base" ).to(A_ ) UpperCamelCase : Tuple = torch.tensor([[1, 2]] , device=A_ ) UpperCamelCase : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=A_ ) # forward pass with torch.no_grad(): UpperCamelCase : Optional[int] = model(input_ids=A_ , bbox=A_ ) UpperCamelCase : List[str] = torch.Size([1, 2, 768] ) UpperCamelCase : Any = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=A_ , ) self.assertTrue(outputs.last_hidden_state.shape , A_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , A_ , atol=1e-3 ) )
52
0
from manim import * class _lowerCamelCase( _a ): def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Union[str, Any] = Rectangle(height=0.5, width=0.5) _lowercase : List[Any] = Rectangle(height=0.4_6, width=0.4_6).set_stroke(width=0) _lowercase : Tuple = [mem.copy() for i in range(6)] _lowercase : Any = [mem.copy() for i in range(6)] _lowercase : str = VGroup(*lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : List[str] = VGroup(*lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : Union[str, Any] = VGroup(lowerCamelCase, lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : List[Any] = Text('CPU', font_size=24) _lowercase : Optional[Any] = Group(lowerCamelCase, lowerCamelCase).arrange(lowerCamelCase, buff=0.5, aligned_edge=lowerCamelCase) cpu.move_to([-2.5, -0.5, 0]) self.add(lowerCamelCase) _lowercase : Dict = [mem.copy() for i in range(4)] _lowercase : Union[str, Any] = VGroup(*lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : int = Text('GPU', font_size=24) _lowercase : str = Group(lowerCamelCase, lowerCamelCase).arrange(lowerCamelCase, buff=0.5, aligned_edge=lowerCamelCase) gpu.move_to([-1, -1, 0]) self.add(lowerCamelCase) _lowercase : str = [mem.copy() for i in range(6)] _lowercase : Optional[int] = VGroup(*lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : Union[str, Any] = Text('Model', font_size=24) _lowercase : Any = Group(lowerCamelCase, lowerCamelCase).arrange(lowerCamelCase, buff=0.5, aligned_edge=lowerCamelCase) model.move_to([3, -1.0, 0]) self.add(lowerCamelCase) _lowercase : Any = [] for i, rect in enumerate(lowerCamelCase): rect.set_stroke(lowerCamelCase) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) _lowercase : Dict = Rectangle(height=0.4_6 / 4, width=0.4_6 / 3).set_stroke(width=0.0).set_fill(lowerCamelCase, opacity=0.7) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT), buff=0.0_2, direction=lowerCamelCase) cpu_target.set_x(cpu_target.get_x() + 0.1) elif i == 3: cpu_target.next_to(cpu_targs[0], direction=lowerCamelCase, buff=0.0) else: cpu_target.next_to(cpu_targs[i - 1], direction=lowerCamelCase, buff=0.0) self.add(lowerCamelCase) cpu_targs.append(lowerCamelCase) _lowercase : Tuple = [mem.copy() for i in range(6)] _lowercase : Any = VGroup(*lowerCamelCase).arrange(lowerCamelCase, buff=0) _lowercase : List[str] = Text('Loaded Checkpoint', font_size=24) _lowercase : int = Group(lowerCamelCase, lowerCamelCase).arrange(lowerCamelCase, aligned_edge=lowerCamelCase, buff=0.4) checkpoint.move_to([3, 0.5, 0]) _lowercase : List[str] = Square(side_length=2.2) key.move_to([-5, 2, 0]) _lowercase : Dict = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''', font_size=18, ) key_text.move_to([-5, 2.4, 0]) self.add(lowerCamelCase, lowerCamelCase) _lowercase : int = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''', font_size=18, ) blue_text.next_to(lowerCamelCase, DOWN * 2.4, aligned_edge=key_text.get_left()) _lowercase : Any = MarkupText( F'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.''', font_size=24, ) step_a.move_to([2, 2, 0]) self.play(Write(lowerCamelCase), Write(lowerCamelCase)) self.play(Write(lowerCamelCase, run_time=1), Create(lowerCamelCase, run_time=1)) _lowercase : Union[str, Any] = [] _lowercase : int = [] for i, rect in enumerate(lowerCamelCase): _lowercase : Any = fill.copy().set_fill(lowerCamelCase, opacity=0.7) target.move_to(lowerCamelCase) first_animations.append(GrowFromCenter(lowerCamelCase, run_time=1)) _lowercase : List[Any] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1]) else: cpu_target.target.move_to(cpu_right_col_base[i - 5]) second_animations.append(MoveToTarget(lowerCamelCase, run_time=1.5)) self.play(*lowerCamelCase) self.play(*lowerCamelCase) self.wait()
21
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __lowerCamelCase : Union[str, Any] = pytest.mark.integration @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_ ) for x in np.arange(30 ).tolist()]} ) return dset def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() UpperCamelCase : List[Any] = dset.map( lambda A_ , A_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=A_ , keep_in_memory=A_ ) UpperCamelCase : List[str] = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase , UpperCamelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCamelCase , UpperCamelCase : int = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A_ , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch UpperCamelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} UpperCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=A_ ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Optional[int] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCamelCase : Any = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[Any] = 1 UpperCamelCase , UpperCamelCase : Optional[Any] = index.search(A_ ) self.assertRaises(A_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCamelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCamelCase , UpperCamelCase : Tuple = index.search_batch(A_ ) self.assertRaises(A_ , index.search_batch , queries[0] ) UpperCamelCase : Optional[int] = [scores[0] for scores in total_scores] UpperCamelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCamelCase : List[str] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(A_ ): UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dict = faiss.IndexFlat(5 ) UpperCamelCase : Union[str, Any] = FaissIndex(custom_index=A_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: index.save(tmp_file.name ) UpperCamelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : int = 1 UpperCamelCase , UpperCamelCase : Dict = index.search(A_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def A_ ( _lowerCAmelCase ) -> Optional[int]: import faiss UpperCamelCase : Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCamelCase : List[Any] = "index.faiss" UpperCamelCase : List[str] = F"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[int] = 1 UpperCamelCase , UpperCamelCase : List[str] = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = Elasticsearch() UpperCamelCase : Union[str, Any] = {"acknowledged": True} UpperCamelCase : Union[str, Any] = ElasticSearchIndex(es_client=A_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query UpperCamelCase : str = "foo" UpperCamelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : Tuple = index.search(A_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCamelCase : Dict = "foo" UpperCamelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : str = index.search(A_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCamelCase : Dict = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Optional[int] = index.search_batch(A_ ) UpperCamelCase : str = [scores[0] for scores in total_scores] UpperCamelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ ) # batched queries with timeout UpperCamelCase : int = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Union[str, Any] = index.search_batch(A_ , request_timeout=30 ) UpperCamelCase : Union[str, Any] = [scores[0] for scores in total_scores] UpperCamelCase : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ )
52
0
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected" , [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10 )]), ({"num_shards": 10, "max_num_jobs": 10}, [range(__lowercase , i + 1 ) for i in range(10 )]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1 )]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCAmelCase_ ( __lowercase : int , __lowercase : Dict ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = _distribute_shards(**__lowercase ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected" , [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ] , ) def UpperCAmelCase_ ( __lowercase : Dict , __lowercase : Optional[Any] , __lowercase : int ) -> str: '''simple docstring''' _UpperCAmelCase = _split_gen_kwargs(__lowercase , __lowercase ) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected" , [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ] , ) def UpperCAmelCase_ ( __lowercase : Optional[Any] , __lowercase : List[Any] ) -> List[Any]: '''simple docstring''' if expected is RuntimeError: with pytest.raises(__lowercase ): _number_of_shards_in_gen_kwargs(__lowercase ) else: _UpperCAmelCase = _number_of_shards_in_gen_kwargs(__lowercase ) assert out == expected
22
def A_ ( _lowerCAmelCase = 50 ) -> int: UpperCamelCase : List[Any] = [[0] * 3 for _ in range(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 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
52
0
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCamelCase__: Union[str, Any] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def snake_case_ ( _lowerCAmelCase : str ) -> Optional[int]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def snake_case_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str ) -> Dict: return max(metric_fn(_lowerCAmelCase , _lowerCAmelCase ) for gt in ground_truths ) def snake_case_ ( _lowerCAmelCase : Any , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[int] ) -> List[str]: UpperCAmelCase : str = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Optional[Any] = [] if args.gold_data_mode == "qa": UpperCAmelCase : Optional[int] = pd.read_csv(_lowerCAmelCase , sep='''\t''' , header=_lowerCAmelCase ) for answer_list in data[1]: UpperCAmelCase : int = ast.literal_eval(_lowerCAmelCase ) answers.append(_lowerCAmelCase ) else: UpperCAmelCase : int = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Optional[Any] = [[reference] for reference in references] UpperCAmelCase : Optional[int] = 0 for prediction, ground_truths in zip(_lowerCAmelCase , _lowerCAmelCase ): total += 1 em += metric_max_over_ground_truths(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) fa += metric_max_over_ground_truths(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = 1_0_0.0 * em / total UpperCAmelCase : Any = 1_0_0.0 * fa / total logger.info(f"""F1: {fa:.2f}""" ) logger.info(f"""EM: {em:.2f}""" ) def snake_case_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] ) -> Optional[Any]: UpperCAmelCase : Union[str, Any] = args.k UpperCAmelCase : Tuple = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Tuple = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Any = 0 for hypo, reference in zip(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase : Dict = set(hypo.split('''\t''' )[:k] ) UpperCAmelCase : Optional[Any] = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k UpperCAmelCase : str = 1_0_0.0 * em / total logger.info(f"""Precision@{k}: {em: .2f}""" ) def snake_case_ ( _lowerCAmelCase : Any , _lowerCAmelCase : int , _lowerCAmelCase : Dict ) -> Optional[int]: def strip_title(_lowerCAmelCase : Optional[int] ): if title.startswith('''"''' ): UpperCAmelCase : Tuple = title[1:] if title.endswith('''"''' ): UpperCAmelCase : Optional[Any] = title[:-1] return title UpperCAmelCase : Union[str, Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _lowerCAmelCase , return_tensors='''pt''' , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , )['''input_ids'''].to(args.device ) UpperCAmelCase : str = rag_model.rag.question_encoder(_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = question_enc_outputs[0] UpperCAmelCase : Any = rag_model.retriever( _lowerCAmelCase , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='''pt''' , ) UpperCAmelCase : int = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) UpperCAmelCase : int = [] for docs in all_docs: UpperCAmelCase : Optional[int] = [strip_title(_lowerCAmelCase ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(_lowerCAmelCase ) ) return provenance_strings def snake_case_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Any , _lowerCAmelCase : Dict ) -> List[str]: with torch.no_grad(): UpperCAmelCase : Any = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _lowerCAmelCase , return_tensors='''pt''' , padding=_lowerCAmelCase , truncation=_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = inputs_dict.input_ids.to(args.device ) UpperCAmelCase : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) UpperCAmelCase : Optional[int] = rag_model.generate( # rag_model overwrites generate _lowerCAmelCase , attention_mask=_lowerCAmelCase , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=_lowerCAmelCase , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) UpperCAmelCase : str = rag_model.retriever.generator_tokenizer.batch_decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase ) if args.print_predictions: for q, a in zip(_lowerCAmelCase , _lowerCAmelCase ): logger.info('''Q: {} - A: {}'''.format(_lowerCAmelCase , _lowerCAmelCase ) ) return answers def snake_case_ ( ) -> List[Any]: UpperCAmelCase : Any = argparse.ArgumentParser() parser.add_argument( '''--model_type''' , choices=['''rag_sequence''', '''rag_token''', '''bart'''] , type=_lowerCAmelCase , help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ) , ) parser.add_argument( '''--index_name''' , default=_lowerCAmelCase , choices=['''exact''', '''compressed''', '''legacy'''] , type=_lowerCAmelCase , help='''RAG model retriever type''' , ) parser.add_argument( '''--index_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , help='''Path to the retrieval index''' , ) parser.add_argument('''--n_docs''' , default=5 , type=_lowerCAmelCase , help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--eval_mode''' , choices=['''e2e''', '''retrieval'''] , default='''e2e''' , type=_lowerCAmelCase , help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ) , ) parser.add_argument('''--k''' , default=1 , type=_lowerCAmelCase , help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to a file containing evaluation samples''' , ) parser.add_argument( '''--gold_data_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to a tab-separated file with gold samples''' , ) parser.add_argument( '''--gold_data_mode''' , default='''qa''' , type=_lowerCAmelCase , choices=['''qa''', '''ans'''] , help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ) , ) parser.add_argument( '''--predictions_path''' , type=_lowerCAmelCase , default='''predictions.txt''' , help='''Name of the predictions file, to be stored in the checkpoints directory''' , ) parser.add_argument( '''--eval_all_checkpoints''' , action='''store_true''' , help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''' , ) parser.add_argument( '''--eval_batch_size''' , default=8 , type=_lowerCAmelCase , help='''Batch size per GPU/CPU for evaluation.''' , ) parser.add_argument( '''--recalculate''' , help='''Recalculate predictions even if the prediction file exists''' , action='''store_true''' , ) parser.add_argument( '''--num_beams''' , default=4 , type=_lowerCAmelCase , help='''Number of beams to be used when generating answers''' , ) parser.add_argument('''--min_length''' , default=1 , type=_lowerCAmelCase , help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''' , default=50 , type=_lowerCAmelCase , help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''' , action='''store_true''' , help='''If True, prints predictions while evaluating.''' , ) parser.add_argument( '''--print_docs''' , action='''store_true''' , help='''If True, prints docs retried while generating.''' , ) UpperCAmelCase : Any = parser.parse_args() UpperCAmelCase : str = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def snake_case_ ( _lowerCAmelCase : Union[str, Any] ) -> int: UpperCAmelCase : int = {} if args.model_type is None: UpperCAmelCase : Union[str, Any] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): UpperCAmelCase : Optional[Any] = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration UpperCAmelCase : Dict = args.n_docs if args.index_name is not None: UpperCAmelCase : Dict = args.index_name if args.index_path is not None: UpperCAmelCase : str = args.index_path else: UpperCAmelCase : int = BartForConditionalGeneration UpperCAmelCase : Optional[Any] = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''' , _lowerCAmelCase ) UpperCAmelCase : str = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k UpperCAmelCase : Any = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(_lowerCAmelCase , args.predictions_path , args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(_lowerCAmelCase ) ) logger.info(''' Batch size = %d''' , args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): UpperCAmelCase : int = RagRetriever.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase : Optional[Any] = model_class.from_pretrained(_lowerCAmelCase , retriever=_lowerCAmelCase , **_lowerCAmelCase ) model.retriever.init_retrieval() else: UpperCAmelCase : Union[str, Any] = model_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) model.to(args.device ) with open(args.evaluation_set , '''r''' ) as eval_file, open(args.predictions_path , '''w''' ) as preds_file: UpperCAmelCase : List[str] = [] for line in tqdm(_lowerCAmelCase ): questions.append(line.strip() ) if len(_lowerCAmelCase ) == args.eval_batch_size: UpperCAmelCase : Any = evaluate_batch_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) preds_file.write('''\n'''.join(_lowerCAmelCase ) + '''\n''' ) preds_file.flush() UpperCAmelCase : str = [] if len(_lowerCAmelCase ) > 0: UpperCAmelCase : Optional[int] = evaluate_batch_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) preds_file.write('''\n'''.join(_lowerCAmelCase ) ) preds_file.flush() score_fn(_lowerCAmelCase , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCamelCase__: List[str] = get_args() main(args)
23
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def A_ ( _lowerCAmelCase ) -> dict[str, str]: UpperCamelCase : Optional[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key UpperCamelCase : Tuple = remove_duplicates(key.upper() ) UpperCamelCase : int = len(_lowerCAmelCase ) # First fill cipher with key characters UpperCamelCase : int = {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_lowerCAmelCase ) , 26 ): UpperCamelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase : List[str] = alphabet[i - offset] UpperCamelCase : List[Any] = char return cipher_alphabet def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: return "".join(cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( ) -> None: UpperCamelCase : int = input("Enter message to encode or decode: " ).strip() UpperCamelCase : str = input("Enter keyword: " ).strip() UpperCamelCase : Union[str, Any] = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: UpperCamelCase : List[str] = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) UpperCamelCase : str = create_cipher_map(_lowerCAmelCase ) print(func(_lowerCAmelCase , _lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
52
0
snake_case_ = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def lowerCamelCase__ ( snake_case_ : str ) -> int: __snake_case = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} __snake_case = 0 __snake_case = 0 while place < len(snake_case_ ): if (place + 1 < len(snake_case_ )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def lowerCamelCase__ ( snake_case_ : int ) -> str: __snake_case = [] for arabic, roman in ROMAN: ((__snake_case) , (__snake_case)) = divmod(snake_case_ , snake_case_ ) result.append(roman * factor ) if number == 0: break return "".join(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod()
24
from sklearn.metrics import fa_score import datasets __lowerCamelCase : List[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCamelCase : List[Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCamelCase : str = """ @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 ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def __UpperCamelCase( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ): '''simple docstring''' UpperCamelCase : List[str] = fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
52
0
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" @slow def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxXLMRobertaModel.from_pretrained("""xlm-roberta-base""" ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""xlm-roberta-base""" ) SCREAMING_SNAKE_CASE__ : int = """The dog is cute and lives in the garden house""" SCREAMING_SNAKE_CASE__ : Any = jnp.array([tokenizer.encode(SCREAMING_SNAKE_CASE__ )] ) SCREAMING_SNAKE_CASE__ : Dict = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim SCREAMING_SNAKE_CASE__ : Optional[int] = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(SCREAMING_SNAKE_CASE__ )["""last_hidden_state"""] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
25
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = KandinskyInpaintPipeline _UpperCAmelCase :List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] _UpperCAmelCase :Dict = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] _UpperCAmelCase :Optional[int] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _UpperCAmelCase :int = False @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCamelCase( self ): '''simple docstring''' return 100 @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : Optional[int] = MultilingualCLIP(A_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase : List[Any] = UNetaDConditionModel(**A_ ) return model @property def __UpperCamelCase( self ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.dummy_text_encoder UpperCamelCase : str = self.dummy_tokenizer UpperCamelCase : List[Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="epsilon" , thresholding=A_ , ) UpperCamelCase : Optional[Any] = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __UpperCamelCase( self , A_ , A_=0 ): '''simple docstring''' UpperCamelCase : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image UpperCamelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(A_ ) ).convert("RGB" ).resize((256, 256) ) # create mask UpperCamelCase : str = np.ones((64, 64) , dtype=np.floataa ) UpperCamelCase : str = 0 if str(A_ ).startswith("mps" ): UpperCamelCase : int = torch.manual_seed(A_ ) else: UpperCamelCase : Tuple = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase : Union[str, Any] = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = "cpu" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**A_ ) UpperCamelCase : Tuple = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase : List[Any] = output.images UpperCamelCase : List[Any] = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase : List[Any] = image[0, -3:, -3:, -1] UpperCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) UpperCamelCase : Union[str, Any] = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __UpperCamelCase( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) UpperCamelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) UpperCamelCase : Dict = np.ones((768, 768) , dtype=np.floataa ) UpperCamelCase : str = 0 UpperCamelCase : List[Any] = "a hat" UpperCamelCase : Tuple = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) UpperCamelCase : Optional[Any] = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[Any] = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() UpperCamelCase : Dict = pipeline( A_ , image=A_ , mask_image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
52
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowercase ( unittest.TestCase ): @slow def a__ ( self ) -> Any: _A : Dict = AutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" , return_dict=_a ).to(_a ) _A : Tuple = AutoTokenizer.from_pretrained("""google/mt5-small""" ) _A : List[Any] = tokenizer("""Hello there""" , return_tensors="""pt""" ).input_ids _A : Optional[int] = tokenizer("""Hi I am""" , return_tensors="""pt""" ).input_ids _A : Dict = model(input_ids.to(_a ) , labels=labels.to(_a ) ).loss _A : Tuple = -(labels.shape[-1] * loss.item()) _A : Union[str, Any] = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
26
class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = set_counts UpperCamelCase : int = max(A_ ) UpperCamelCase : Optional[Any] = len(A_ ) UpperCamelCase : Union[str, Any] = [1] * num_sets UpperCamelCase : Union[str, Any] = list(range(A_ ) ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = self.get_parent(A_ ) UpperCamelCase : Optional[int] = self.get_parent(A_ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] UpperCamelCase : int = 0 UpperCamelCase : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 UpperCamelCase : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] UpperCamelCase : Any = 0 UpperCamelCase : Optional[int] = src_parent UpperCamelCase : int = self.set_counts[src_parent] UpperCamelCase : Any = max(self.max_set , A_ ) return True def __UpperCamelCase( self , A_ ): '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set UpperCamelCase : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
52
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase : List[str] = logging.get_logger(__name__) __lowercase : Dict = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "distilbert" A_ = { "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self , __a=3_0522 , __a=512 , __a=False , __a=6 , __a=12 , __a=768 , __a=4 * 768 , __a=0.1 , __a=0.1 , __a="gelu" , __a=0.02 , __a=0.1 , __a=0.2 , __a=0 , **__a , ): '''simple docstring''' __a : Any = vocab_size __a : List[str] = max_position_embeddings __a : Optional[Any] = sinusoidal_pos_embds __a : int = n_layers __a : Optional[Any] = n_heads __a : Optional[int] = dim __a : Optional[int] = hidden_dim __a : Optional[Any] = dropout __a : Tuple = attention_dropout __a : Dict = activation __a : List[str] = initializer_range __a : Optional[Any] = qa_dropout __a : Optional[int] = seq_classif_dropout super().__init__(**__a , pad_token_id=__a ) class __UpperCamelCase ( lowerCAmelCase_ ): @property def __UpperCAmelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": __a : Dict = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a : Optional[int] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
27
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Any = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
'''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 __lowerCamelCase ( A__ ) -> List[str]: """simple docstring""" UpperCamelCase = [] 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 __lowerCamelCase ( A__ , A__ ) -> Optional[int]: """simple docstring""" UpperCamelCase = [] 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 __lowerCamelCase ( A__ ) -> Any: """simple docstring""" UpperCamelCase = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", 'stage2.cls_token') ) return token def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = [] 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 __lowerCamelCase ( A__ , A__ , A__ , A__ ) -> Any: """simple docstring""" UpperCamelCase = 'imagenet-1k-id2label.json' UpperCamelCase = 1_000 UpperCamelCase = 'huggingface/label-files' UpperCamelCase = num_labels UpperCamelCase = json.load(open(cached_download(hf_hub_url(A__ , A__ , repo_type='dataset' ) ) , 'r' ) ) UpperCamelCase = {int(A__ ): v for k, v in idalabel.items()} UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} UpperCamelCase = UpperCamelCase = 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": UpperCamelCase = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": UpperCamelCase = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: UpperCamelCase = [2, 2, 20] UpperCamelCase = [3, 12, 16] UpperCamelCase = [192, 768, 1_024] UpperCamelCase = CvtForImageClassification(A__ ) UpperCamelCase = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) UpperCamelCase = image_size UpperCamelCase = torch.load(A__ , map_location=torch.device('cpu' ) ) UpperCamelCase = OrderedDict() UpperCamelCase = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: UpperCamelCase = list_of_state_dict + cls_token(A__ ) UpperCamelCase = list_of_state_dict + embeddings(A__ ) for cnt in range(config.depth[idx] ): UpperCamelCase = list_of_state_dict + attention(A__ , A__ ) UpperCamelCase = list_of_state_dict + final() for gg in list_of_state_dict: print(A__ ) for i in range(len(A__ ) ): UpperCamelCase = 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__": _lowerCamelCase : Tuple = 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." ) _lowerCamelCase : Any = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
28
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class A__ ( __snake_case , __snake_case ): _UpperCAmelCase :Optional[int] = 'convnextv2' def __init__( self , A_=3 , A_=4 , A_=4 , A_=None , A_=None , A_="gelu" , A_=0.02 , A_=1e-12 , A_=0.0 , A_=224 , A_=None , A_=None , **A_ , ): '''simple docstring''' super().__init__(**A_ ) UpperCamelCase : Dict = num_channels UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Union[str, Any] = num_stages UpperCamelCase : List[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCamelCase : List[str] = [3, 3, 9, 3] if depths is None else depths UpperCamelCase : Dict = hidden_act UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : str = drop_path_rate UpperCamelCase : List[str] = image_size UpperCamelCase : List[str] = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase : str = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
52
0
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) __UpperCAmelCase = { 'sample_size': 32, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': 1000, 'block_out_channels': [32, 64], 'attention_head_dim': 8, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } __UpperCAmelCase = { 'sample_size': 64, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 3, 'num_class_embeds': 1000, 'block_out_channels': [192, 192 * 2, 192 * 3, 192 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } __UpperCAmelCase = { 'sample_size': 256, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': None, 'block_out_channels': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'default', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } __UpperCAmelCase = { 'num_train_timesteps': 40, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } __UpperCAmelCase = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } __UpperCAmelCase = { 'num_train_timesteps': 151, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } def lowercase__ ( __snake_case : int ): '''simple docstring''' if isinstance(__snake_case , __snake_case ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('boolean value expected' ) def lowercase__ ( __snake_case : Any , __snake_case : Dict , __snake_case : List[Any] , __snake_case : str , __snake_case : Dict=False ): '''simple docstring''' UpperCAmelCase_ : Union[str, Any] = checkpoint[F"{old_prefix}.in_layers.0.weight"] UpperCAmelCase_ : str = checkpoint[F"{old_prefix}.in_layers.0.bias"] UpperCAmelCase_ : Dict = checkpoint[F"{old_prefix}.in_layers.2.weight"] UpperCAmelCase_ : Optional[Any] = checkpoint[F"{old_prefix}.in_layers.2.bias"] UpperCAmelCase_ : int = checkpoint[F"{old_prefix}.emb_layers.1.weight"] UpperCAmelCase_ : Any = checkpoint[F"{old_prefix}.emb_layers.1.bias"] UpperCAmelCase_ : List[str] = checkpoint[F"{old_prefix}.out_layers.0.weight"] UpperCAmelCase_ : Tuple = checkpoint[F"{old_prefix}.out_layers.0.bias"] UpperCAmelCase_ : Dict = checkpoint[F"{old_prefix}.out_layers.3.weight"] UpperCAmelCase_ : Optional[int] = checkpoint[F"{old_prefix}.out_layers.3.bias"] if has_skip: UpperCAmelCase_ : Tuple = checkpoint[F"{old_prefix}.skip_connection.weight"] UpperCAmelCase_ : List[str] = checkpoint[F"{old_prefix}.skip_connection.bias"] return new_checkpoint def lowercase__ ( __snake_case : Dict , __snake_case : List[Any] , __snake_case : Optional[int] , __snake_case : int , __snake_case : Dict=None ): '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Dict = checkpoint[F"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = checkpoint[F"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) UpperCAmelCase_ : Dict = checkpoint[F"{old_prefix}.norm.weight"] UpperCAmelCase_ : int = checkpoint[F"{old_prefix}.norm.bias"] UpperCAmelCase_ : Tuple = weight_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : str = bias_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : Any = weight_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : List[Any] = bias_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : Dict = weight_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : Optional[Any] = bias_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase_ : Any = ( checkpoint[F"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) UpperCAmelCase_ : Optional[int] = checkpoint[F"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def lowercase__ ( __snake_case : str , __snake_case : Any ): '''simple docstring''' UpperCAmelCase_ : Any = torch.load(__snake_case , map_location='cpu' ) UpperCAmelCase_ : int = {} UpperCAmelCase_ : Optional[int] = checkpoint['time_embed.0.weight'] UpperCAmelCase_ : str = checkpoint['time_embed.0.bias'] UpperCAmelCase_ : str = checkpoint['time_embed.2.weight'] UpperCAmelCase_ : str = checkpoint['time_embed.2.bias'] if unet_config["num_class_embeds"] is not None: UpperCAmelCase_ : Any = checkpoint['label_emb.weight'] UpperCAmelCase_ : Dict = checkpoint['input_blocks.0.0.weight'] UpperCAmelCase_ : List[str] = checkpoint['input_blocks.0.0.bias'] UpperCAmelCase_ : List[Any] = unet_config['down_block_types'] UpperCAmelCase_ : Any = unet_config['layers_per_block'] UpperCAmelCase_ : Optional[Any] = unet_config['attention_head_dim'] UpperCAmelCase_ : Union[str, Any] = unet_config['block_out_channels'] UpperCAmelCase_ : List[str] = 1 UpperCAmelCase_ : str = channels_list[0] for i, layer_type in enumerate(__snake_case ): UpperCAmelCase_ : List[Any] = channels_list[i] UpperCAmelCase_ : Union[str, Any] = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(__snake_case ): UpperCAmelCase_ : Tuple = F"down_blocks.{i}.resnets.{j}" UpperCAmelCase_ : Dict = F"input_blocks.{current_layer}.0" UpperCAmelCase_ : Union[str, Any] = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase_ : Optional[int] = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case , has_skip=__snake_case ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(__snake_case ): UpperCAmelCase_ : Optional[int] = F"down_blocks.{i}.resnets.{j}" UpperCAmelCase_ : str = F"input_blocks.{current_layer}.0" UpperCAmelCase_ : Dict = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase_ : int = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case , has_skip=__snake_case ) UpperCAmelCase_ : Dict = F"down_blocks.{i}.attentions.{j}" UpperCAmelCase_ : List[Any] = F"input_blocks.{current_layer}.1" UpperCAmelCase_ : List[str] = convert_attention( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) current_layer += 1 if i != len(__snake_case ) - 1: UpperCAmelCase_ : Dict = F"down_blocks.{i}.downsamplers.0" UpperCAmelCase_ : Optional[Any] = F"input_blocks.{current_layer}.0" UpperCAmelCase_ : Any = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case ) current_layer += 1 UpperCAmelCase_ : Optional[int] = current_channels # hardcoded the mid-block for now UpperCAmelCase_ : int = 'mid_block.resnets.0' UpperCAmelCase_ : Optional[Any] = 'middle_block.0' UpperCAmelCase_ : Union[str, Any] = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case ) UpperCAmelCase_ : Optional[Any] = 'mid_block.attentions.0' UpperCAmelCase_ : Union[str, Any] = 'middle_block.1' UpperCAmelCase_ : List[Any] = convert_attention(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) UpperCAmelCase_ : int = 'mid_block.resnets.1' UpperCAmelCase_ : Dict = 'middle_block.2' UpperCAmelCase_ : str = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case ) UpperCAmelCase_ : int = 0 UpperCAmelCase_ : Union[str, Any] = unet_config['up_block_types'] for i, layer_type in enumerate(__snake_case ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase_ : Dict = F"up_blocks.{i}.resnets.{j}" UpperCAmelCase_ : Dict = F"output_blocks.{current_layer}.0" UpperCAmelCase_ : Dict = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case , has_skip=__snake_case ) current_layer += 1 if i != len(__snake_case ) - 1: UpperCAmelCase_ : Dict = F"up_blocks.{i}.upsamplers.0" UpperCAmelCase_ : Optional[Any] = F"output_blocks.{current_layer-1}.1" UpperCAmelCase_ : int = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase_ : Optional[int] = F"up_blocks.{i}.resnets.{j}" UpperCAmelCase_ : List[Any] = F"output_blocks.{current_layer}.0" UpperCAmelCase_ : int = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case , has_skip=__snake_case ) UpperCAmelCase_ : List[str] = F"up_blocks.{i}.attentions.{j}" UpperCAmelCase_ : Optional[Any] = F"output_blocks.{current_layer}.1" UpperCAmelCase_ : Optional[Any] = convert_attention( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) current_layer += 1 if i != len(__snake_case ) - 1: UpperCAmelCase_ : List[str] = F"up_blocks.{i}.upsamplers.0" UpperCAmelCase_ : List[str] = F"output_blocks.{current_layer-1}.2" UpperCAmelCase_ : str = convert_resnet(__snake_case , __snake_case , __snake_case , __snake_case ) UpperCAmelCase_ : Optional[Any] = checkpoint['out.0.weight'] UpperCAmelCase_ : str = checkpoint['out.0.bias'] UpperCAmelCase_ : List[str] = checkpoint['out.2.weight'] UpperCAmelCase_ : str = checkpoint['out.2.bias'] return new_checkpoint if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--unet_path', default=None, type=str, required=True, help='Path to the unet.pt to convert.') parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output the converted UNet model.' ) parser.add_argument('--class_cond', default=True, type=str, help='Whether the model is class-conditional.') __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = strabool(args.class_cond) __UpperCAmelCase = os.path.basename(args.unet_path) print(F'Checkpoint: {ckpt_name}') # Get U-Net config if "imagenet64" in ckpt_name: __UpperCAmelCase = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __UpperCAmelCase = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: __UpperCAmelCase = TEST_UNET_CONFIG else: raise ValueError(F'Checkpoint type {ckpt_name} is not currently supported.') if not args.class_cond: __UpperCAmelCase = None __UpperCAmelCase = con_pt_to_diffuser(args.unet_path, unet_config) __UpperCAmelCase = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: __UpperCAmelCase = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: __UpperCAmelCase = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): __UpperCAmelCase = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F'Checkpoint type {ckpt_name} is not currently supported.') __UpperCAmelCase = CMStochasticIterativeScheduler(**scheduler_config) __UpperCAmelCase = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
29
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_lowerCAmelCase ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def A_ ( ) -> Tuple: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def A_ ( ) -> Optional[int]: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_lowerCAmelCase ): http_head("https://huggingface.co" )
52
0
def a ( snake_case__: int = 100 ): '''simple docstring''' lowercase_ = (n * (n + 1) // 2) ** 2 lowercase_ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
30
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
'''simple docstring''' import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' def __init__( self : List[str] , **A : Tuple ): requires_backends(self , ["bs4"] ) super().__init__(**A ) def _A ( self : Any , A : Any ): _UpperCAmelCase : List[str] = [] _UpperCAmelCase : str = [] _UpperCAmelCase : int = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag _UpperCAmelCase : Any = parent.find_all(child.name , recursive=A ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(A ) else next(i for i, s in enumerate(A , 1 ) if s is child ) ) _UpperCAmelCase : Dict = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : List[str] , A : List[Any] ): _UpperCAmelCase : Tuple = BeautifulSoup(A , "html.parser" ) _UpperCAmelCase : Optional[int] = [] _UpperCAmelCase : Union[str, Any] = [] _UpperCAmelCase : Optional[int] = [] for element in html_code.descendants: if type(A ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue _UpperCAmelCase : Optional[Any] = html.unescape(A ).strip() if not text_in_this_tag: continue all_doc_strings.append(A ) _UpperCAmelCase , _UpperCAmelCase : int = self.xpath_soup(A ) stringaxtag_seq.append(A ) stringaxsubs_seq.append(A ) if len(A ) != len(A ): raise ValueError("Number of doc strings and xtags does not correspond" ) if len(A ) != len(A ): raise ValueError("Number of doc strings and xsubs does not correspond" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : Optional[int] , A : Tuple , A : Tuple ): _UpperCAmelCase : str = "" for tagname, subs in zip(A , A ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Optional[Any] , A : str ): _UpperCAmelCase : int = False # Check that strings has a valid type if isinstance(A , A ): _UpperCAmelCase : Optional[int] = True elif isinstance(A , (list, tuple) ): if len(A ) == 0 or isinstance(html_strings[0] , A ): _UpperCAmelCase : List[Any] = True if not valid_strings: raise ValueError( "HTML strings must of type `str`, `List[str]` (batch of examples), " F"""but is of type {type(A )}.""" ) _UpperCAmelCase : List[str] = bool(isinstance(A , (list, tuple) ) and (isinstance(html_strings[0] , A )) ) if not is_batched: _UpperCAmelCase : Tuple = [html_strings] # Get nodes + xpaths _UpperCAmelCase : List[str] = [] _UpperCAmelCase : str = [] for html_string in html_strings: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Dict = self.get_three_from_single(A ) nodes.append(A ) _UpperCAmelCase : Optional[int] = [] for node, tag_list, sub_list in zip(A , A , A ): _UpperCAmelCase : Dict = self.construct_xpath(A , A ) xpath_strings.append(A ) xpaths.append(A ) # return as Dict _UpperCAmelCase : str = {"nodes": nodes, "xpaths": xpaths} _UpperCAmelCase : Any = BatchFeature(data=A , tensor_type=A ) return encoded_inputs
31
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCamelCase : List[Any] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ __lowerCamelCase : Optional[int] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ __lowerCamelCase : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def A_ ( _lowerCAmelCase ) -> str: def remove_articles(_lowerCAmelCase ): UpperCamelCase : Tuple = re.compile(r"\b(a|an|the)\b" , re.UNICODE ) return re.sub(_lowerCAmelCase , " " , _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase ): UpperCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = [any(compute_exact(_lowerCAmelCase , _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 100 def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Optional[int] = Counter(_lowerCAmelCase ) UpperCamelCase : List[Any] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : Tuple = scount * numref UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Tuple = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Dict = ccount * numref # KEEP UpperCamelCase : List[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Union[str, Any] = keepgramcounter_rep & rgramcounter UpperCamelCase : Dict = sgramcounter_rep & rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Any = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Union[str, Any] = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : Any = sgramcounter_rep - cgramcounter_rep UpperCamelCase : str = delgramcounter_rep - rgramcounter UpperCamelCase : Any = sgramcounter_rep - rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Dict = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : str = deltmpscorea / len(_lowerCAmelCase ) # ADDITION UpperCamelCase : List[str] = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : List[str] = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) UpperCamelCase : Dict = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 UpperCamelCase : Tuple = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Tuple = addtmpscore / len(_lowerCAmelCase ) UpperCamelCase : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : List[str] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: UpperCamelCase : int = len(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = ssent.split(" " ) UpperCamelCase : Dict = csent.split(" " ) UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Any = [] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : str = [] UpperCamelCase : str = [] UpperCamelCase : Dict = [] UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = [] for rsent in rsents: UpperCamelCase : List[Any] = rsent.split(" " ) UpperCamelCase : List[str] = [] UpperCamelCase : int = [] UpperCamelCase : Tuple = [] ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : List[Any] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : List[str] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : str = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : Union[str, Any] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Union[str, Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = "13a" , _lowerCAmelCase = True ) -> Optional[Any]: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : Dict = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : str = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: UpperCamelCase : Dict = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": UpperCamelCase : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase , escape=_lowerCAmelCase ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase ) else: UpperCamelCase : Union[str, Any] = sentence if not return_str: UpperCamelCase : Tuple = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError("Sources length must match predictions and references lengths." ) UpperCamelCase : Optional[Any] = 0 for src, pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ) , normalize(_lowerCAmelCase ) , [normalize(_lowerCAmelCase ) for sent in refs] ) UpperCamelCase : Optional[int] = sari_score / len(_lowerCAmelCase ) return 100 * sari_score def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase="exp" , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> List[str]: UpperCamelCase : Optional[Any] = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] UpperCamelCase : Tuple = sacrebleu.corpus_bleu( _lowerCAmelCase , _lowerCAmelCase , smooth_method=_lowerCAmelCase , smooth_value=_lowerCAmelCase , force=_lowerCAmelCase , lowercase=_lowerCAmelCase , use_effective_order=_lowerCAmelCase , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = {} result.update({"sari": compute_sari(sources=A_ , predictions=A_ , references=A_ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A_ , references=A_ )} ) result.update({"exact": compute_em(predictions=A_ , references=A_ )} ) return result
52
0
import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Union[str, Any]: """simple docstring""" a_ : Dict = SwinConfig(image_size=1_92 ) if "base" in model_name: a_ : List[str] = 6 a_ : int = 1_28 a_ : Tuple = (2, 2, 18, 2) a_ : Optional[int] = (4, 8, 16, 32) elif "large" in model_name: a_ : List[str] = 12 a_ : Union[str, Any] = 1_92 a_ : Union[str, Any] = (2, 2, 18, 2) a_ : str = (6, 12, 24, 48) else: raise ValueError('Model not supported, only supports base and large variants' ) a_ : List[str] = window_size a_ : Any = embed_dim a_ : Optional[int] = depths a_ : List[Any] = num_heads return config def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Optional[int]: """simple docstring""" if "encoder.mask_token" in name: a_ : Dict = name.replace('encoder.mask_token' , 'embeddings.mask_token' ) if "encoder.patch_embed.proj" in name: a_ : int = name.replace('encoder.patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "encoder.patch_embed.norm" in name: a_ : Tuple = name.replace('encoder.patch_embed.norm' , 'embeddings.norm' ) if "attn.proj" in name: a_ : int = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: a_ : Union[str, Any] = name.replace('attn' , 'attention.self' ) if "norm1" in name: a_ : Dict = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: a_ : int = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: a_ : Tuple = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: a_ : Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": a_ : Optional[int] = 'layernorm.weight' if name == "encoder.norm.bias": a_ : Union[str, Any] = 'layernorm.bias' if "decoder" in name: pass else: a_ : List[str] = 'swin.' + name return name def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] , __A : Tuple ) -> List[str]: """simple docstring""" for key in orig_state_dict.copy().keys(): a_ : List[str] = orig_state_dict.pop(__A ) if "attn_mask" in key: pass elif "qkv" in key: a_ : int = key.split('.' ) a_ : Dict = int(key_split[2] ) a_ : Union[str, Any] = int(key_split[4] ) a_ : Dict = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a_ : int = val[:dim, :] a_ : Optional[Any] = val[ dim : dim * 2, : ] a_ : List[str] = val[-dim:, :] else: a_ : Union[str, Any] = val[ :dim ] a_ : Dict = val[ dim : dim * 2 ] a_ : Tuple = val[ -dim: ] else: a_ : int = val return orig_state_dict def SCREAMING_SNAKE_CASE_ ( __A : str , __A : Any , __A : str , __A : Optional[int] ) -> Union[str, Any]: """simple docstring""" a_ : str = torch.load(__A , map_location='cpu' )['model'] a_ : Union[str, Any] = get_swin_config(__A ) a_ : List[str] = SwinForMaskedImageModeling(__A ) model.eval() a_ : Dict = convert_state_dict(__A , __A ) model.load_state_dict(__A ) a_ : List[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' a_ : List[str] = ViTImageProcessor(size={'height': 1_92, 'width': 1_92} ) a_ : Optional[Any] = Image.open(requests.get(__A , stream=__A ).raw ) a_ : List[str] = image_processor(images=__A , return_tensors='pt' ) with torch.no_grad(): a_ : str = model(**__A ).logits print(outputs.keys() ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__A ) if push_to_hub: print(F"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(F"""microsoft/{model_name}""" ) image_processor.push_to_hub(F"""microsoft/{model_name}""" ) if __name__ == "__main__": UpperCAmelCase_ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='swin-base-simmim-window6-192', type=str, choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'], help='Name of the Swin SimMIM model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth', type=str, help='Path to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
32
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : str = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = 'roberta' def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Any = type_vocab_size UpperCamelCase : int = initializer_range UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = position_embedding_type UpperCamelCase : Any = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
52
0
"""simple docstring""" import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer __A : List[str] = logging.get_logger(__name__) __A : Optional[Any] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } __A : int = { '''allenai/led-base-16384''': 16_384, } class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Optional[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ : List[str] = LEDTokenizer SCREAMING_SNAKE_CASE_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : int , A : Any=None , A : Optional[Any]=None , A : List[Any]=None , A : Optional[int]="replace" , A : Tuple="<s>" , A : List[str]="</s>" , A : Optional[int]="</s>" , A : List[Any]="<s>" , A : Optional[Any]="<unk>" , A : Optional[int]="<pad>" , A : Optional[Any]="<mask>" , A : Any=False , A : Union[str, Any]=True , **A : Union[str, Any] , ) -> int: super().__init__( A , A , tokenizer_file=A , errors=A , bos_token=A , eos_token=A , sep_token=A , cls_token=A , unk_token=A , pad_token=A , mask_token=A , add_prefix_space=A , trim_offsets=A , **A , ) lowercase_ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , A ) != add_prefix_space: lowercase_ : List[str] = getattr(A , pre_tok_state.pop('''type''' ) ) lowercase_ : int = add_prefix_space lowercase_ : Tuple = pre_tok_class(**A ) lowercase_ : int = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` lowercase_ : List[str] = '''post_processor''' lowercase_ : List[Any] = getattr(self.backend_tokenizer , A , A ) if tokenizer_component_instance: lowercase_ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowercase_ : Dict = tuple(state['''sep'''] ) if "cls" in state: lowercase_ : Union[str, Any] = tuple(state['''cls'''] ) lowercase_ : Dict = False if state.get('''add_prefix_space''' , A ) != add_prefix_space: lowercase_ : Union[str, Any] = add_prefix_space lowercase_ : Union[str, Any] = True if state.get('''trim_offsets''' , A ) != trim_offsets: lowercase_ : Union[str, Any] = trim_offsets lowercase_ : str = True if changes_to_apply: lowercase_ : int = getattr(A , state.pop('''type''' ) ) lowercase_ : Tuple = component_class(**A ) setattr(self.backend_tokenizer , A , A ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def A ( self : Optional[Any] ) -> str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def A ( self : Optional[int] , A : int ) -> str: lowercase_ : str = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else value lowercase_ : Optional[Any] = value def A ( self : Optional[Any] , *A : str , **A : Optional[Any] ) -> BatchEncoding: lowercase_ : int = kwargs.get('''is_split_into_words''' , A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*A , **A ) def A ( self : List[Any] , *A : int , **A : List[str] ) -> BatchEncoding: lowercase_ : str = kwargs.get('''is_split_into_words''' , A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*A , **A ) def A ( self : Any , A : str , A : Optional[str] = None ) -> Tuple[str]: lowercase_ : str = self._tokenizer.model.save(A , name=A ) return tuple(A ) def A ( self : Any , A : str , A : Union[str, Any]=None ) -> Any: lowercase_ : Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def A ( self : Union[str, Any] , A : List[int] , A : Optional[List[int]] = None ) -> List[int]: lowercase_ : Optional[Any] = [self.sep_token_id] lowercase_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def A ( self : Optional[Any] , A : Union[Dict[str, EncodedInput], BatchEncoding] , A : Optional[int] = None , A : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , A : Optional[int] = None , A : Optional[bool] = None , ) -> dict: lowercase_ : Any = super()._pad( encoded_inputs=A , max_length=A , padding_strategy=A , pad_to_multiple_of=A , return_attention_mask=A , ) # Load from model defaults if return_attention_mask is None: lowercase_ : Optional[Any] = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: lowercase_ : Optional[int] = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. lowercase_ : Tuple = len(encoded_inputs['''global_attention_mask'''] ) != len(A ) if needs_to_be_padded: lowercase_ : Union[str, Any] = len(A ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` lowercase_ : Dict = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": lowercase_ : str = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
33
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_case ): def __init__( self , A_ , A_ ): '''simple docstring''' super().__init__() self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = 100 , A_ = None , A_ = None , A_ = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCamelCase : str = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) UpperCamelCase : Union[str, Any] = int(A_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : List[str] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) UpperCamelCase : Any = int(A_ ) UpperCamelCase : Union[str, Any] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : Optional[int] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(A_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) UpperCamelCase : Optional[Any] = randn_tensor(A_ , generator=A_ , device=self.device , dtype=A_ ) # set step values self.scheduler.set_timesteps(A_ , device=audio.device ) UpperCamelCase : Optional[int] = self.scheduler.timesteps.to(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(A_ , A_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : int = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase : Optional[Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A_ )
52
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _a ( __a , unittest.TestCase ): __a : Any = KandinskyVaaImgaImgPipeline __a : Optional[int] = ["""image_embeds""", """negative_image_embeds""", """image"""] __a : int = [ """image_embeds""", """negative_image_embeds""", """image""", ] __a : Any = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __a : Union[str, Any] = False @property def A ( self : List[Any] ): '''simple docstring''' return 32 @property def A ( self : Dict ): '''simple docstring''' return 32 @property def A ( self : str ): '''simple docstring''' return self.time_input_dim @property def A ( self : Dict ): '''simple docstring''' return self.time_input_dim * 4 @property def A ( self : Optional[int] ): '''simple docstring''' return 100 @property def A ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase = { '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } UpperCAmelCase = UNetaDConditionModel(**lowercase ) return model @property def A ( self : Any ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def A ( self : Any ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def A ( self : List[Any] ): '''simple docstring''' UpperCAmelCase = self.dummy_unet UpperCAmelCase = self.dummy_movq UpperCAmelCase = { '''num_train_timesteps''': 1_000, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } UpperCAmelCase = DDIMScheduler(**lowercase ) UpperCAmelCase = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def A ( self : Optional[int] , lowercase : int , lowercase : List[Any]=0 ): '''simple docstring''' UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowercase ) ).to(lowercase ) UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowercase ) # create init_image UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase ) ).to(lowercase ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase = Image.fromarray(np.uinta(lowercase ) ).convert('''RGB''' ).resize((256, 256) ) if str(lowercase ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(lowercase ) else: UpperCAmelCase = torch.Generator(device=lowercase ).manual_seed(lowercase ) UpperCAmelCase = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def A ( self : Tuple ): '''simple docstring''' UpperCAmelCase = '''cpu''' UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = self.pipeline_class(**lowercase ) UpperCAmelCase = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase = pipe(**self.get_dummy_inputs(lowercase ) ) UpperCAmelCase = output.images UpperCAmelCase = pipe( **self.get_dummy_inputs(lowercase ) , return_dict=lowercase , )[0] UpperCAmelCase = image[0, -3:, -3:, -1] UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase = np.array( [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class _a ( unittest.TestCase ): def A ( self : List[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : int ): '''simple docstring''' UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) UpperCAmelCase = '''A red cartoon frog, 4k''' UpperCAmelCase = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(lowercase ) UpperCAmelCase = KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipeline.to(lowercase ) pipeline.set_progress_bar_config(disable=lowercase ) UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase , UpperCAmelCase = pipe_prior( lowercase , generator=lowercase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() UpperCAmelCase = pipeline( image=lowercase , image_embeds=lowercase , negative_image_embeds=lowercase , generator=lowercase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , ) UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase , lowercase )
34
import functools def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: UpperCamelCase : Optional[int] = len(_lowerCAmelCase ) UpperCamelCase : List[str] = len(_lowerCAmelCase ) @functools.cache def min_distance(_lowerCAmelCase , _lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa UpperCamelCase : Union[str, Any] = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _lowerCAmelCase ) , 1 + min_distance(_lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
52
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
35
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __lowerCamelCase : str = random.Random() if is_torch_available(): import torch def A_ ( _lowerCAmelCase , _lowerCAmelCase=1.0 , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: if rng is None: UpperCamelCase : Optional[int] = global_rng UpperCamelCase : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class A__ ( unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ): '''simple docstring''' UpperCamelCase : Tuple = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Union[str, Any] = feature_size UpperCamelCase : List[str] = padding_value UpperCamelCase : Optional[Any] = sampling_rate UpperCamelCase : List[str] = return_attention_mask UpperCamelCase : List[Any] = do_normalize def __UpperCamelCase( self ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCamelCase( self , A_=False , A_=False ): '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: UpperCamelCase : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Dict = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Union[str, Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = ASTFeatureExtractor def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = ASTFeatureExtractionTester(self ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Dict = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCamelCase : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(A_ ) UpperCamelCase : Any = feat_extract(A_ , return_tensors="np" ).input_values UpperCamelCase : List[str] = feat_extract(A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) @require_torch def __UpperCamelCase( self ): '''simple docstring''' import torch UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : str = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __UpperCamelCase( self , A_ ): '''simple docstring''' from datasets import load_dataset UpperCamelCase : Dict = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech UpperCamelCase : Any = ds.sort("id" ).select(range(A_ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : Tuple = ASTFeatureExtractor() UpperCamelCase : str = feature_extractor(A_ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A_ , atol=1e-4 ) )
52
0
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( a , unittest.TestCase): lowerCamelCase__ = FunnelTokenizer lowerCamelCase__ = FunnelTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def snake_case__ ( self): '''simple docstring''' super().setUp() _lowerCAmelCase : Any = [ "<unk>", "<cls>", "<sep>", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _lowerCAmelCase : str = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def snake_case__ ( self, **__a): '''simple docstring''' return FunnelTokenizer.from_pretrained(self.tmpdirname, **__a) def snake_case__ ( self, **__a): '''simple docstring''' return FunnelTokenizerFast.from_pretrained(self.tmpdirname, **__a) def snake_case__ ( self, __a): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = "UNwant\u00E9d,running" _lowerCAmelCase : Tuple = "unwanted, running" return input_text, output_text def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[Any] = self.tokenizer_class(self.vocab_file) _lowerCAmelCase : Dict = tokenizer.tokenize("UNwant\u00E9d,running") self.assertListEqual(__a, ["un", "##want", "##ed", ",", "runn", "##ing"]) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a), [7, 4, 5, 10, 8, 9]) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.get_tokenizers(do_lower_case=__a) for tokenizer in tokenizers: _lowerCAmelCase : Optional[Any] = tokenizer("UNwant\u00E9d,running") _lowerCAmelCase : Union[str, Any] = len(inputs["input_ids"]) - 1 self.assertListEqual(inputs["token_type_ids"], [2] + [0] * sentence_len) _lowerCAmelCase : Any = tokenizer("UNwant\u00E9d,running", "UNwant\u00E9d,running") self.assertListEqual(inputs["token_type_ids"], [2] + [0] * sentence_len + [1] * sentence_len)
36
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ): '''simple docstring''' UpperCamelCase : int = bp_numa UpperCamelCase : int = bp_numa UpperCamelCase : List[Any] = bp_numa UpperCamelCase : Optional[int] = conva_get[:2] UpperCamelCase : Optional[Any] = conva_get[2] UpperCamelCase : Dict = size_pa UpperCamelCase : Union[str, Any] = rate_w UpperCamelCase : Dict = rate_t UpperCamelCase : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] UpperCamelCase : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : Optional[Any] = -2 * np.random.rand(self.conva[1] ) + 1 UpperCamelCase : Any = -2 * np.random.rand(self.num_bpa ) + 1 UpperCamelCase : int = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(A_ , "wb" ) as f: pickle.dump(A_ , A_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __UpperCamelCase( cls , A_ ): '''simple docstring''' with open(A_ , "rb" ) as f: UpperCamelCase : Optional[Any] = pickle.load(A_ ) # noqa: S301 UpperCamelCase : List[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) UpperCamelCase : Union[str, Any] = model_dic.get("size_pooling1" ) UpperCamelCase : List[Any] = model_dic.get("num_bp1" ) UpperCamelCase : Dict = model_dic.get("num_bp2" ) UpperCamelCase : Dict = model_dic.get("num_bp3" ) UpperCamelCase : Dict = model_dic.get("rate_weight" ) UpperCamelCase : str = model_dic.get("rate_thre" ) # create model instance UpperCamelCase : Any = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter UpperCamelCase : str = model_dic.get("w_conv1" ) UpperCamelCase : Optional[Any] = model_dic.get("wkj" ) UpperCamelCase : int = model_dic.get("vji" ) UpperCamelCase : Any = model_dic.get("thre_conv1" ) UpperCamelCase : Optional[int] = model_dic.get("thre_bp2" ) UpperCamelCase : Union[str, Any] = model_dic.get("thre_bp3" ) return conv_ins def __UpperCamelCase( self , A_ ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def __UpperCamelCase( self , A_ ): '''simple docstring''' return round(A_ , 3 ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = convs[0] UpperCamelCase : Optional[Any] = convs[1] UpperCamelCase : Optional[Any] = np.shape(A_ )[0] # get the data slice of original image data, data_focus UpperCamelCase : List[str] = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): UpperCamelCase : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): UpperCamelCase : str = [] for i_focus in range(len(A_ ) ): UpperCamelCase : List[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) UpperCamelCase : Optional[int] = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion UpperCamelCase : List[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) UpperCamelCase : Tuple = np.asarray(A_ ) return focus_list, data_featuremap def __UpperCamelCase( self , A_ , A_ , A_="average_pool" ): '''simple docstring''' UpperCamelCase : Any = len(featuremaps[0] ) UpperCamelCase : str = int(size_map / size_pooling ) UpperCamelCase : Optional[int] = [] for i_map in range(len(A_ ) ): UpperCamelCase : Tuple = featuremaps[i_map] UpperCamelCase : Any = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): UpperCamelCase : int = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) UpperCamelCase : Optional[Any] = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = [] for i in range(len(A_ ) ): UpperCamelCase : List[Any] = np.shape(data[i] ) UpperCamelCase : str = data[i].reshape(1 , shapes[0] * shapes[1] ) UpperCamelCase : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) UpperCamelCase : Any = np.asarray(A_ ) return data_expanded def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = np.asarray(A_ ) UpperCamelCase : List[Any] = np.shape(A_ ) UpperCamelCase : Any = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[int] = 0 for i_map in range(A_ ): UpperCamelCase : int = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): UpperCamelCase : str = pd_pool[ i_pool ] UpperCamelCase : str = i_pool + 1 UpperCamelCase : str = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=bool ): '''simple docstring''' print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(A_ )) ) print((" - - Shape: Teach_Data ", np.shape(A_ )) ) UpperCamelCase : List[str] = 0 UpperCamelCase : Union[str, Any] = [] UpperCamelCase : int = 1_0000 while rp < n_repeat and mse >= error_accuracy: UpperCamelCase : Tuple = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) UpperCamelCase : Any = np.asmatrix(datas_train[p] ) UpperCamelCase : List[str] = np.asarray(datas_teach[p] ) UpperCamelCase , UpperCamelCase : Dict = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : Tuple = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : int = np.shape(A_ ) UpperCamelCase : List[str] = self._expand(A_ ) UpperCamelCase : Optional[int] = data_bp_input UpperCamelCase : str = np.dot(A_ , self.vji.T ) - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) UpperCamelCase : List[Any] = np.dot(A_ , self.wkj.T ) - self.thre_bpa UpperCamelCase : Dict = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- UpperCamelCase : List[Any] = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : str = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : Any = np.dot(A_ , self.vji ) UpperCamelCase : Dict = pd_i_all / (self.size_poolinga * self.size_poolinga) UpperCamelCase : List[Any] = pd_conva_pooled.T.getA().tolist() UpperCamelCase : List[Any] = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): UpperCamelCase : List[Any] = self._expand_mat(pd_conva_all[k_conv] ) UpperCamelCase : List[Any] = self.rate_weight * np.dot(A_ , A_ ) UpperCamelCase : str = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) UpperCamelCase : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer UpperCamelCase : Optional[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight UpperCamelCase : List[Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight UpperCamelCase : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre UpperCamelCase : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image UpperCamelCase : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) UpperCamelCase : Any = rp + 1 UpperCamelCase : Union[str, Any] = error_count / patterns all_mse.append(A_ ) def draw_error(): UpperCamelCase : Tuple = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , "+-" ) plt.plot(A_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(A_ )) ) for p in range(len(A_ ) ): UpperCamelCase : int = np.asmatrix(datas_test[p] ) UpperCamelCase , UpperCamelCase : Any = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : List[str] = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : Dict = self._expand(A_ ) UpperCamelCase : List[Any] = data_bp_input UpperCamelCase : Any = bp_outa * self.vji.T - self.thre_bpa UpperCamelCase : List[Any] = self.sig(A_ ) UpperCamelCase : int = bp_outa * self.wkj.T - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) UpperCamelCase : List[str] = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = np.asmatrix(A_ ) UpperCamelCase , UpperCamelCase : List[Any] = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : str = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
52
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Any = 0 while b > 0: if b & 1: lowerCAmelCase__ : Tuple = ((res % c) + (a % c)) % c a += a b >>= 1 return res
37
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Any = { """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""", # See all BART models at https://huggingface.co/models?filter=bart } class A__ ( __snake_case ): _UpperCAmelCase :Dict = 'bart' _UpperCAmelCase :str = ['past_key_values'] _UpperCAmelCase :Any = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , A_=5_0265 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=3 , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , **A_ , ): '''simple docstring''' UpperCamelCase : int = vocab_size UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Any = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = encoder_attention_heads UpperCamelCase : Optional[int] = decoder_ffn_dim UpperCamelCase : List[str] = decoder_layers UpperCamelCase : Optional[int] = decoder_attention_heads UpperCamelCase : int = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Tuple = activation_dropout UpperCamelCase : Tuple = activation_function UpperCamelCase : int = init_std UpperCamelCase : List[Any] = encoder_layerdrop UpperCamelCase : List[str] = decoder_layerdrop UpperCamelCase : Dict = classifier_dropout UpperCamelCase : Optional[int] = use_cache UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , A_ ): UpperCamelCase : 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." ) class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase : List[str] = {0: "batch"} UpperCamelCase : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase : Dict = {0: "batch", 1: "decoder_sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(A_ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase : Any = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase , UpperCamelCase : Optional[int] = self.num_layers for i in range(A_ ): UpperCamelCase : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase : Optional[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Tuple = super().outputs else: UpperCamelCase : Dict = super(A_ , self ).outputs if self.use_past: UpperCamelCase , UpperCamelCase : int = self.num_layers for i in range(A_ ): UpperCamelCase : int = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Tuple = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) # Generate decoder inputs UpperCamelCase : List[Any] = seq_length if not self.use_past else 1 UpperCamelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) UpperCamelCase : Optional[int] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase : List[Any] = dict(**A_ , **A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Optional[Any] = common_inputs["input_ids"].shape UpperCamelCase : List[Any] = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase , UpperCamelCase : List[str] = self.num_attention_heads UpperCamelCase : int = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : List[Any] = decoder_seq_length + 3 UpperCamelCase : str = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase : int = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(A_ , A_ )] , dim=1 ) UpperCamelCase : int = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase , UpperCamelCase : Union[str, Any] = self.num_layers UpperCamelCase : Any = min(A_ , A_ ) UpperCamelCase : List[str] = max(A_ , A_ ) - min_num_layers UpperCamelCase : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(A_ ): common_inputs["past_key_values"].append( ( torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), ) ) # TODO: test this. UpperCamelCase : Optional[Any] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(A_ , A_ ): common_inputs["past_key_values"].append((torch.zeros(A_ ), torch.zeros(A_ )) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : int = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Union[str, Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase : Optional[Any] = seqlen + 2 UpperCamelCase , UpperCamelCase : List[Any] = self.num_layers UpperCamelCase , UpperCamelCase : Optional[int] = self.num_attention_heads UpperCamelCase : str = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : Optional[Any] = common_inputs["attention_mask"].dtype UpperCamelCase : int = torch.cat( [common_inputs["attention_mask"], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) UpperCamelCase : Optional[Any] = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(A_ ) ] return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase : Union[str, Any] = tokenizer.num_special_tokens_to_add(A_ ) UpperCamelCase : int = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase : int = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase : Dict = dict(tokenizer(A_ , return_tensors=A_ ) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) elif self.task == "causal-lm": UpperCamelCase : List[str] = self._generate_dummy_inputs_for_causal_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) else: UpperCamelCase : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) return common_inputs def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[Any] = super()._flatten_past_key_values_(A_ , A_ , A_ , A_ ) else: UpperCamelCase : Optional[Any] = super(A_ , self )._flatten_past_key_values_( A_ , A_ , A_ , A_ )
52
0
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging UpperCAmelCase_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , __lowerCamelCase : CLIPSegForImageSegmentation , __lowerCamelCase : CLIPSegProcessor , __lowerCamelCase : AutoencoderKL , __lowerCamelCase : CLIPTextModel , __lowerCamelCase : CLIPTokenizer , __lowerCamelCase : UNetaDConditionModel , __lowerCamelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __lowerCamelCase : StableDiffusionSafetyChecker , __lowerCamelCase : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , """steps_offset""" ) and scheduler.config.steps_offset != 1: UpperCamelCase :str = ( F"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" F""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ """to update the config accordingly as leaving `steps_offset` might led to incorrect results""" """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,""" """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`""" """ file""" ) deprecate("""steps_offset!=1""" , """1.0.0""" , __lowerCamelCase , standard_warn=__lowerCamelCase ) UpperCamelCase :Optional[Any] = dict(scheduler.config ) UpperCamelCase :Tuple = 1 UpperCamelCase :Dict = FrozenDict(__lowerCamelCase ) if hasattr(scheduler.config , """skip_prk_steps""" ) and scheduler.config.skip_prk_steps is False: UpperCamelCase :Any = ( F"""The configuration file of this scheduler: {scheduler} has not set the configuration""" """ `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make""" """ sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to""" """ incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face""" """ Hub, it would be very nice if you could open a Pull request for the""" """ `scheduler/scheduler_config.json` file""" ) deprecate("""skip_prk_steps not set""" , """1.0.0""" , __lowerCamelCase , standard_warn=__lowerCamelCase ) UpperCamelCase :Tuple = dict(scheduler.config ) UpperCamelCase :Any = True UpperCamelCase :List[str] = FrozenDict(__lowerCamelCase ) if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( segmentation_model=__lowerCamelCase , segmentation_processor=__lowerCamelCase , vae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , unet=__lowerCamelCase , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , ) def _A ( self : Dict , __lowerCamelCase : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase :Optional[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__lowerCamelCase ) def _A ( self : Union[str, Any] ): self.enable_attention_slicing(__lowerCamelCase ) def _A ( self : Union[str, Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) UpperCamelCase :Any = torch.device("""cuda""" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__lowerCamelCase , __lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _A ( self : Tuple ): if self.device != torch.device("""meta""" ) or not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__lowerCamelCase , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : Optional[Any] , __lowerCamelCase : Union[str, List[str]] , __lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , __lowerCamelCase : str , __lowerCamelCase : int = 512 , __lowerCamelCase : int = 512 , __lowerCamelCase : int = 50 , __lowerCamelCase : float = 7.5 , __lowerCamelCase : Optional[Union[str, List[str]]] = None , __lowerCamelCase : Optional[int] = 1 , __lowerCamelCase : float = 0.0 , __lowerCamelCase : Optional[torch.Generator] = None , __lowerCamelCase : Optional[torch.FloatTensor] = None , __lowerCamelCase : Optional[str] = "pil" , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowerCamelCase : int = 1 , **__lowerCamelCase : List[Any] , ): UpperCamelCase :Any = self.segmentation_processor( text=[text] , images=[image] , padding="""max_length""" , return_tensors="""pt""" ).to(self.device ) UpperCamelCase :Any = self.segmentation_model(**__lowerCamelCase ) UpperCamelCase :Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCamelCase :Optional[int] = self.numpy_to_pil(__lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCamelCase :Tuple = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__lowerCamelCase , image=__lowerCamelCase , mask_image=__lowerCamelCase , height=__lowerCamelCase , width=__lowerCamelCase , num_inference_steps=__lowerCamelCase , guidance_scale=__lowerCamelCase , negative_prompt=__lowerCamelCase , num_images_per_prompt=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , latents=__lowerCamelCase , output_type=__lowerCamelCase , return_dict=__lowerCamelCase , callback=__lowerCamelCase , callback_steps=__lowerCamelCase , )
38
from math import sqrt def A_ ( _lowerCAmelCase ) -> bool: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" UpperCamelCase : List[Any] = True # 0 and 1 are none primes. if number <= 1: UpperCamelCase : List[Any] = False for divisor in range(2 , int(round(sqrt(_lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCamelCase : Union[str, Any] = False break # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'status' must been from type bool" return status def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCamelCase : int = list(range(2 , n + 1 ) ) UpperCamelCase : Optional[int] = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_lowerCAmelCase ) ): for j in range(i + 1 , len(_lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCamelCase : Tuple = 0 # filters actual prime numbers. UpperCamelCase : str = [x for x in begin_list if x != 0] # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" UpperCamelCase : str = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(_lowerCAmelCase ): ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" UpperCamelCase : Optional[Any] = [] # this list will be returns of the function. # potential prime number factors. UpperCamelCase : Tuple = 2 UpperCamelCase : str = number if number == 0 or number == 1: ans.append(_lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_lowerCAmelCase ): while quotient != 1: if is_prime(_lowerCAmelCase ) and (quotient % factor == 0): ans.append(_lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Any = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = max(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Union[str, Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Dict = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = min(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def A_ ( _lowerCAmelCase ) -> List[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def A_ ( _lowerCAmelCase ) -> Any: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (number > 2) and is_even(_lowerCAmelCase ) ), "'number' must been an int, even and > 2" UpperCamelCase : List[str] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCamelCase : Dict = get_prime_numbers(_lowerCAmelCase ) UpperCamelCase : Tuple = len(_lowerCAmelCase ) # run variable for while-loops. UpperCamelCase : Optional[int] = 0 UpperCamelCase : int = None # exit variable. for break up the loops UpperCamelCase : Union[str, Any] = True while i < len_pn and loop: UpperCamelCase : Tuple = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCamelCase : Any = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (len(_lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Tuple = 0 while numbera != 0: UpperCamelCase : Tuple = numbera % numbera UpperCamelCase : Any = numbera UpperCamelCase : Union[str, Any] = rest # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Optional[int] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCamelCase : List[Any] = prime_factorization(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = prime_factorization(_lowerCAmelCase ) elif numbera == 1 or numbera == 1: UpperCamelCase : Optional[Any] = [] UpperCamelCase : int = [] UpperCamelCase : List[Any] = max(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 UpperCamelCase : List[str] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) UpperCamelCase : Tuple = prime_fac_a.count(_lowerCAmelCase ) for _ in range(max(_lowerCAmelCase , _lowerCAmelCase ) ): ans *= n else: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCamelCase : Any = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" UpperCamelCase : int = 0 UpperCamelCase : int = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_lowerCAmelCase ): ans += 1 # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and is_prime( _lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( is_prime(_lowerCAmelCase ) and is_prime(_lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCamelCase : str = p_number_a + 1 # jump to the next number UpperCamelCase : Dict = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(_lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ans[0] != p_number_a and ans[len(_lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def A_ ( _lowerCAmelCase ) -> List[str]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" UpperCamelCase : Dict = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(_lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def A_ ( _lowerCAmelCase ) -> int: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCamelCase : int = get_divisors(_lowerCAmelCase ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(_lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCamelCase : List[str] = gcd(abs(_lowerCAmelCase ) , abs(_lowerCAmelCase ) ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def A_ ( _lowerCAmelCase ) -> Dict: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" UpperCamelCase : str = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" UpperCamelCase : Dict = 0 UpperCamelCase : Dict = 1 UpperCamelCase : Union[str, Any] = 1 # this will be return for _ in range(n - 1 ): UpperCamelCase : Any = ans ans += fiba UpperCamelCase : str = tmp return ans
52
0
import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __lowerCamelCase ( snake_case__ , snake_case__ , unittest.TestCase): """simple docstring""" UpperCamelCase__ = IFInpaintingPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCamelCase__ = PipelineTesterMixin.required_optional_params - {"latents"} def UpperCamelCase ( self ): """simple docstring""" return self._get_dummy_components() def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=0 ): """simple docstring""" if str(UpperCAmelCase ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(UpperCAmelCase ) else: _UpperCAmelCase = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) _UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) _UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) _UpperCAmelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCamelCase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def UpperCamelCase ( self ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def UpperCamelCase ( self ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCamelCase ( self ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCamelCase ( self ): """simple docstring""" self._test_save_load_local() def UpperCamelCase ( self ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
39
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 : str = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCamelCase : Tuple = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCamelCase : List[str] = 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 : Optional[Any] = re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") __lowerCamelCase : List[str] = { """DecisionTransformerConfig""", """EncoderDecoderConfig""", """MusicgenConfig""", """RagConfig""", """SpeechEncoderDecoderConfig""", """TimmBackboneConfig""", """VisionEncoderDecoderConfig""", """VisionTextDualEncoderConfig""", """LlamaConfig""", } def A_ ( _lowerCAmelCase ) -> List[str]: UpperCamelCase : Optional[Any] = None # source code of `config_class` UpperCamelCase : Tuple = inspect.getsource(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = _re_checkpoint.findall(_lowerCAmelCase ) # 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 : Dict = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase : Any = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: UpperCamelCase : List[Any] = ckpt_name break return checkpoint def A_ ( ) -> List[str]: UpperCamelCase : Optional[int] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCamelCase : Union[str, Any] = get_checkpoint_from_config_class(_lowerCAmelCase ) UpperCamelCase : Optional[int] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Any = "\n".join(sorted(_lowerCAmelCase ) ) raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
52
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowercase ( A_ )-> int: '''simple docstring''' a : Any = filter(lambda A_ : p.requires_grad , model.parameters() ) a : Optional[int] = sum([np.prod(p.size() ) for p in model_parameters] ) return params __lowercase = logging.getLogger(__name__) def lowercase ( A_ , A_ )-> Dict: '''simple docstring''' if metric == "rouge2": a : Union[str, Any] = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": a : Any = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": a : Optional[int] = "{val_avg_em:.4f}-{step_count}" elif metric == "loss": a : Optional[Any] = "{val_avg_loss:.4f}-{step_count}" else: raise NotImplementedError( F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' " function." ) a : Union[str, Any] = ModelCheckpoint( dirpath=A_ , filename=A_ , monitor=F'''val_{metric}''' , mode="max" , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def lowercase ( A_ , A_ )-> List[str]: '''simple docstring''' return EarlyStopping( monitor=F'''val_{metric}''' , mode="min" if "loss" in metric else "max" , patience=A_ , verbose=A_ , ) class _A ( pl.Callback ): """simple docstring""" def __snake_case ( self : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : int): a : Optional[Any] = {f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups)} pl_module.logger.log_metrics(__UpperCAmelCase) @rank_zero_only def __snake_case ( self : Tuple , __UpperCAmelCase : pl.Trainer , __UpperCAmelCase : pl.LightningModule , __UpperCAmelCase : str , __UpperCAmelCase : Any=True): logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''') a : Dict = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}) # Log results a : Optional[Any] = Path(pl_module.hparams.output_dir) if type_path == "test": a : str = od / "test_results.txt" a : str = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. a : str = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' a : List[Any] = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=__UpperCAmelCase) generations_file.parent.mkdir(exist_ok=__UpperCAmelCase) with open(__UpperCAmelCase , "a+") as writer: for key in sorted(__UpperCAmelCase): if key in ["log", "progress_bar", "preds"]: continue a : List[str] = metrics[key] if isinstance(__UpperCAmelCase , torch.Tensor): a : str = val.item() a : Dict = f'''{key}: {val:.6f}\n''' writer.write(__UpperCAmelCase) if not save_generations: return if "preds" in metrics: a : Any = "\n".join(metrics["preds"]) generations_file.open("w+").write(__UpperCAmelCase) @rank_zero_only def __snake_case ( self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict): try: a : Optional[Any] = pl_module.model.model.num_parameters() except AttributeError: a : Any = pl_module.model.num_parameters() a : Dict = count_trainable_parameters(__UpperCAmelCase) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}) @rank_zero_only def __snake_case ( self : str , __UpperCAmelCase : pl.Trainer , __UpperCAmelCase : pl.LightningModule): save_json(pl_module.metrics , pl_module.metrics_save_path) return self._write_logs(__UpperCAmelCase , __UpperCAmelCase , "test") @rank_zero_only def __snake_case ( self : Dict , __UpperCAmelCase : pl.Trainer , __UpperCAmelCase : Union[str, Any]): save_json(pl_module.metrics , pl_module.metrics_save_path) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
40
from __future__ import annotations from functools import lru_cache from math import ceil __lowerCamelCase : str = 100 __lowerCamelCase : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __lowerCamelCase : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def A_ ( _lowerCAmelCase ) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} UpperCamelCase : set[int] = set() UpperCamelCase : int UpperCamelCase : int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A_ ( _lowerCAmelCase = 5000 ) -> int | None: for number_to_partition in range(1 , _lowerCAmelCase ): if len(partition(_lowerCAmelCase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
52
0
'''simple docstring''' import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _A : Optional[Any] =logging.getLogger(__name__) _A : Dict ='''pytorch_model.bin''' @dataclasses.dataclass class _lowercase : a = dataclasses.field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models."""} ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co."""} , ) @dataclasses.dataclass class _lowercase : a = dataclasses.field(metadata={"""help""": """A csv or a json file containing the training data."""} ) a = dataclasses.field(metadata={"""help""": """A csv or a json file containing the data to predict on."""} ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """A csv or a json file containing the validation data."""} ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """The name of the task to train on."""} , ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """The list of labels for the task."""} ) @dataclasses.dataclass class _lowercase : a = dataclasses.field( metadata={"""help""": """The output directory where the model predictions and checkpoints will be written."""} ) a = dataclasses.field( default="""accuracy""" , metadata={"""help""": """The evaluation metric used for the task."""} ) a = dataclasses.field( default="""no""" , metadata={ """help""": """The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]""" } , ) a = dataclasses.field( default=10 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a = dataclasses.field( default=0.0 , metadata={ """help""": """How much the specified evaluation metric must improve to satisfy early stopping conditions.""" } , ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the confidence score."""} , ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the validation performance."""} , ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """Whether to fine-tune on labeled data after pseudo training."""} , ) a = dataclasses.field( default=0.0 , metadata={"""help""": """Confidence threshold for pseudo-labeled data filtering."""} , ) a = dataclasses.field( default=100 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a = dataclasses.field( default=_lowercase , metadata={"""help""": """Random seed for initialization."""} , ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : str = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: lowerCamelCase__ : Optional[int] = dataset.filter(lambda UpperCamelCase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 lowerCamelCase__ : Any = int(eval_result * len(UpperCamelCase ) ) print(UpperCamelCase ) lowerCamelCase__ : Any = dataset.sort("""probability""" , reverse=UpperCamelCase ) lowerCamelCase__ : int = dataset.select(range(UpperCamelCase ) ) lowerCamelCase__ : List[str] = dataset.remove_columns(["""label""", """probability"""] ) lowerCamelCase__ : Union[str, Any] = dataset.rename_column("""prediction""" , """label""" ) lowerCamelCase__ : List[Any] = dataset.map(lambda UpperCamelCase : {"label": idalabel[example["label"]]} ) lowerCamelCase__ : Tuple = dataset.shuffle(seed=args.seed ) lowerCamelCase__ : List[Any] = os.path.join(UpperCamelCase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(UpperCamelCase , index=UpperCamelCase ) else: dataset.to_json(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , **UpperCamelCase ) -> str: lowerCamelCase__ : List[str] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() lowerCamelCase__ : List[str] = STModelArguments(model_name_or_path=UpperCamelCase ) lowerCamelCase__ : Optional[Any] = STDataArguments(train_file=UpperCamelCase , infer_file=UpperCamelCase ) lowerCamelCase__ : Dict = STTrainingArguments(output_dir=UpperCamelCase ) lowerCamelCase__ : Optional[int] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCamelCase ).items(): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) for key, value in kwargs.items(): if hasattr(UpperCamelCase , UpperCamelCase ): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # Sanity checks lowerCamelCase__ : List[Any] = {} lowerCamelCase__ : Optional[int] = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None lowerCamelCase__ : str = args.train_file lowerCamelCase__ : Tuple = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None lowerCamelCase__ : Optional[int] = args.eval_file for key in data_files: lowerCamelCase__ : Dict = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: lowerCamelCase__ : Any = extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) lowerCamelCase__ : int = f'''{args.output_dir}/self-train_iter-{{}}'''.format lowerCamelCase__ : List[Any] = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCamelCase ) os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) accelerator.wait_for_everyone() lowerCamelCase__ : Dict = None lowerCamelCase__ : Any = None lowerCamelCase__ : Optional[int] = 0 lowerCamelCase__ : Dict = False # Show the progress bar lowerCamelCase__ : List[str] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): lowerCamelCase__ : int = data_dir_format(UpperCamelCase ) assert os.path.exists(UpperCamelCase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 lowerCamelCase__ : str = os.path.join(UpperCamelCase , """stage-1""" ) lowerCamelCase__ : Dict = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCamelCase , UpperCamelCase ): arguments_dict.update({key: value} ) lowerCamelCase__ : int = os.path.join(UpperCamelCase , """best-checkpoint""" , UpperCamelCase ) if os.path.exists(UpperCamelCase ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCamelCase , UpperCamelCase , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCamelCase ) finetune(**UpperCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCamelCase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data lowerCamelCase__ : Tuple = os.path.join(UpperCamelCase , """best-checkpoint""" ) lowerCamelCase__ : List[Any] = os.path.join(UpperCamelCase , """stage-2""" ) # Update arguments_dict lowerCamelCase__ : Tuple = model_path lowerCamelCase__ : Union[str, Any] = data_files["""train"""] lowerCamelCase__ : List[str] = current_output_dir lowerCamelCase__ : int = os.path.join(UpperCamelCase , """best-checkpoint""" , UpperCamelCase ) if os.path.exists(UpperCamelCase ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCamelCase , UpperCamelCase , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCamelCase ) finetune(**UpperCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(UpperCamelCase ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCamelCase ) lowerCamelCase__ : Optional[Any] = iteration lowerCamelCase__ : Any = data_dir_format(iteration + 1 ) lowerCamelCase__ : Tuple = AutoConfig.from_pretrained(os.path.join(UpperCamelCase , """best-checkpoint""" ) ) lowerCamelCase__ : Optional[int] = config.idalabel lowerCamelCase__ : str = os.path.join(UpperCamelCase , """eval_results_best-checkpoint.json""" ) lowerCamelCase__ : Any = os.path.join(UpperCamelCase , """test_results_best-checkpoint.json""" ) assert os.path.exists(UpperCamelCase ) with open(UpperCamelCase , """r""" ) as f: lowerCamelCase__ : Union[str, Any] = float(json.load(UpperCamelCase )[args.eval_metric] ) lowerCamelCase__ : Any = os.path.join(UpperCamelCase , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(UpperCamelCase ) # Loading the dataset from local csv or json files. lowerCamelCase__ : str = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] lowerCamelCase__ : Dict = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) shutil.copy(UpperCamelCase , os.path.join(UpperCamelCase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(UpperCamelCase ): shutil.copy(UpperCamelCase , os.path.join(UpperCamelCase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) accelerator.wait_for_everyone() lowerCamelCase__ : Optional[Any] = os.path.join(UpperCamelCase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: lowerCamelCase__ : List[str] = eval_result if best_iteration is None: lowerCamelCase__ : Tuple = new_iteration lowerCamelCase__ : Any = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: lowerCamelCase__ : Dict = new_iteration lowerCamelCase__ : int = new_eval_result lowerCamelCase__ : Any = 0 else: if new_eval_result == best_eval_result: lowerCamelCase__ : Any = new_iteration lowerCamelCase__ : int = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: lowerCamelCase__ : List[Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , UpperCamelCase ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(UpperCamelCase , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCamelCase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(UpperCamelCase , """eval_results_best-iteration.json""" ) , )
41
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Optional[int] = int(_lowerCAmelCase ) if decimal in (0, 1): # Exit cases for the recursion return str(_lowerCAmelCase ) UpperCamelCase , UpperCamelCase : Dict = divmod(_lowerCAmelCase , 2 ) return binary_recursive(_lowerCAmelCase ) + str(_lowerCAmelCase ) def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = str(_lowerCAmelCase ).strip() if not number: raise ValueError("No input value was provided" ) UpperCamelCase : Optional[int] = "-" if number.startswith("-" ) else "" UpperCamelCase : Any = number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return F"""{negative}0b{binary_recursive(int(_lowerCAmelCase ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
52
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = 42 class __UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase ): @register_to_config def __init__( self , lowerCAmelCase_ = 16 , lowerCAmelCase_ = 88 , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = 32 , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = "geglu" , lowerCAmelCase_ = True , lowerCAmelCase_ = True , ): """simple docstring""" super().__init__() _snake_case = num_attention_heads _snake_case = attention_head_dim _snake_case = num_attention_heads * attention_head_dim _snake_case = in_channels _snake_case = torch.nn.GroupNorm(num_groups=lowerCAmelCase_ , num_channels=lowerCAmelCase_ , eps=1E-6 , affine=lowerCAmelCase_ ) _snake_case = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ ) # 3. Define transformers blocks _snake_case = nn.ModuleList( [ BasicTransformerBlock( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dropout=lowerCAmelCase_ , cross_attention_dim=lowerCAmelCase_ , activation_fn=lowerCAmelCase_ , attention_bias=lowerCAmelCase_ , double_self_attention=lowerCAmelCase_ , norm_elementwise_affine=lowerCAmelCase_ , ) for d in range(lowerCAmelCase_ ) ] ) _snake_case = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=1 , lowerCAmelCase_=None , lowerCAmelCase_ = True , ): """simple docstring""" _snake_case , _snake_case , _snake_case , _snake_case = hidden_states.shape _snake_case = batch_frames // num_frames _snake_case = hidden_states _snake_case = hidden_states[None, :].reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) _snake_case = self.norm(lowerCAmelCase_ ) _snake_case = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = self.proj_in(lowerCAmelCase_ ) # 2. Blocks for block in self.transformer_blocks: _snake_case = block( lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , timestep=lowerCAmelCase_ , cross_attention_kwargs=lowerCAmelCase_ , class_labels=lowerCAmelCase_ , ) # 3. Output _snake_case = self.proj_out(lowerCAmelCase_ ) _snake_case = ( hidden_states[None, None, :] .reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) _snake_case = hidden_states.reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=lowerCAmelCase_ )
42
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=24 , A_=2 , A_=6 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=None , A_=1000 , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : Dict = seq_length UpperCamelCase : Tuple = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : Optional[Any] = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : Optional[int] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : Optional[int] = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Optional[int] = scope UpperCamelCase : int = range_bbox def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase : Union[str, Any] = bbox[i, j, 3] UpperCamelCase : int = bbox[i, j, 1] UpperCamelCase : int = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : List[str] = bbox[i, j, 2] UpperCamelCase : Optional[int] = bbox[i, j, 0] UpperCamelCase : Optional[Any] = t UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : str = None if self.use_token_type_ids: UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Dict = None UpperCamelCase : int = None if self.use_labels: UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCamelCase( self ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = LiltModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = model(A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ ) UpperCamelCase : Optional[int] = model(A_ , bbox=A_ , token_type_ids=A_ ) UpperCamelCase : Any = model(A_ , bbox=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = self.num_labels UpperCamelCase : Dict = LiltForTokenClassification(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Dict = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Dict = LiltForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Tuple = config_and_inputs UpperCamelCase : Tuple = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) _UpperCAmelCase :Dict = False _UpperCAmelCase :Union[str, Any] = False def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' return True def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = LiltModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = LiltModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @slow class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base" ).to(A_ ) UpperCamelCase : Tuple = torch.tensor([[1, 2]] , device=A_ ) UpperCamelCase : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=A_ ) # forward pass with torch.no_grad(): UpperCamelCase : Optional[int] = model(input_ids=A_ , bbox=A_ ) UpperCamelCase : List[str] = torch.Size([1, 2, 768] ) UpperCamelCase : Any = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=A_ , ) self.assertTrue(outputs.last_hidden_state.shape , A_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , A_ , atol=1e-3 ) )
52
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowercase , __lowercase=7 , __lowercase=3 , __lowercase=18 , __lowercase=30 , __lowercase=400 , __lowercase=True , __lowercase=None , __lowercase=True , __lowercase=None , __lowercase=True , ) -> Dict: __UpperCamelCase :Union[str, Any] = size if size is not None else {'''shortest_edge''': 20} __UpperCamelCase :List[str] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __UpperCamelCase :int = parent __UpperCamelCase :Union[str, Any] = batch_size __UpperCamelCase :Tuple = num_channels __UpperCamelCase :Tuple = image_size __UpperCamelCase :List[Any] = min_resolution __UpperCamelCase :Tuple = max_resolution __UpperCamelCase :Tuple = do_resize __UpperCamelCase :Any = size __UpperCamelCase :Optional[int] = do_center_crop __UpperCamelCase :int = crop_size __UpperCamelCase :Optional[int] = do_flip_channel_order def UpperCamelCase__ ( self) -> Any: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class lowerCamelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Optional[int] = MobileViTImageProcessor if is_vision_available() else None def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :int = MobileViTImageProcessingTester(self) @property def UpperCamelCase__ ( self) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self) -> str: __UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__lowercase , '''do_resize''')) self.assertTrue(hasattr(__lowercase , '''size''')) self.assertTrue(hasattr(__lowercase , '''do_center_crop''')) self.assertTrue(hasattr(__lowercase , '''center_crop''')) self.assertTrue(hasattr(__lowercase , '''do_flip_channel_order''')) def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'''shortest_edge''': 20}) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18}) __UpperCamelCase :Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84) self.assertEqual(image_processor.size , {'''shortest_edge''': 42}) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84}) def UpperCamelCase__ ( self) -> Optional[Any]: pass def UpperCamelCase__ ( self) -> List[Any]: # Initialize image_processing __UpperCamelCase :List[str] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __UpperCamelCase :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image) # Test not batched input __UpperCamelCase :int = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __UpperCamelCase :str = image_processing(__lowercase , 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) -> Dict: # Initialize image_processing __UpperCamelCase :Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __UpperCamelCase :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , numpify=__lowercase) for image in image_inputs: self.assertIsInstance(__lowercase , np.ndarray) # Test not batched input __UpperCamelCase :List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __UpperCamelCase :Optional[int] = image_processing(__lowercase , 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) -> List[str]: # Initialize image_processing __UpperCamelCase :List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __UpperCamelCase :Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , torchify=__lowercase) for image in image_inputs: self.assertIsInstance(__lowercase , torch.Tensor) # Test not batched input __UpperCamelCase :Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __UpperCamelCase :Optional[int] = image_processing(__lowercase , 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'''], ) , )
43
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __lowerCamelCase : Union[str, Any] = pytest.mark.integration @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_ ) for x in np.arange(30 ).tolist()]} ) return dset def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() UpperCamelCase : List[Any] = dset.map( lambda A_ , A_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=A_ , keep_in_memory=A_ ) UpperCamelCase : List[str] = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase , UpperCamelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCamelCase , UpperCamelCase : int = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A_ , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch UpperCamelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} UpperCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=A_ ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Optional[int] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCamelCase : Any = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[Any] = 1 UpperCamelCase , UpperCamelCase : Optional[Any] = index.search(A_ ) self.assertRaises(A_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCamelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCamelCase , UpperCamelCase : Tuple = index.search_batch(A_ ) self.assertRaises(A_ , index.search_batch , queries[0] ) UpperCamelCase : Optional[int] = [scores[0] for scores in total_scores] UpperCamelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCamelCase : List[str] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(A_ ): UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dict = faiss.IndexFlat(5 ) UpperCamelCase : Union[str, Any] = FaissIndex(custom_index=A_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: index.save(tmp_file.name ) UpperCamelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : int = 1 UpperCamelCase , UpperCamelCase : Dict = index.search(A_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def A_ ( _lowerCAmelCase ) -> Optional[int]: import faiss UpperCamelCase : Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCamelCase : List[Any] = "index.faiss" UpperCamelCase : List[str] = F"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[int] = 1 UpperCamelCase , UpperCamelCase : List[str] = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = Elasticsearch() UpperCamelCase : Union[str, Any] = {"acknowledged": True} UpperCamelCase : Union[str, Any] = ElasticSearchIndex(es_client=A_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query UpperCamelCase : str = "foo" UpperCamelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : Tuple = index.search(A_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCamelCase : Dict = "foo" UpperCamelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : str = index.search(A_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCamelCase : Dict = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Optional[int] = index.search_batch(A_ ) UpperCamelCase : str = [scores[0] for scores in total_scores] UpperCamelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ ) # batched queries with timeout UpperCamelCase : int = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Union[str, Any] = index.search_batch(A_ , request_timeout=30 ) UpperCamelCase : Union[str, Any] = [scores[0] for scores in total_scores] UpperCamelCase : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ )
52
0
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = XGLMTokenizer _UpperCamelCase : List[Any] = XGLMTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : Tuple = True def __A ( self ): super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self ): _lowerCAmelCase : List[str] = """<pad>""" _lowerCAmelCase : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def __A ( self ): _lowerCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(a__ ) , 1008 ) def __A ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __A ( self ): _lowerCAmelCase : List[Any] = XGLMTokenizer(a__ , keep_accents=a__ ) _lowerCAmelCase : Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Any = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __A ( self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def __A ( self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a__ , f.name ) _lowerCAmelCase : Union[str, Any] = XGLMTokenizer(f.name , keep_accents=a__ ) _lowerCAmelCase : List[str] = pickle.dumps(a__ ) pickle.loads(a__ ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = self.get_rust_tokenizer() _lowerCAmelCase : Tuple = """I was born in 92000, and this is falsé.""" _lowerCAmelCase : List[Any] = tokenizer.tokenize(a__ ) _lowerCAmelCase : Tuple = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : Union[str, Any] = tokenizer.encode(a__ , add_special_tokens=a__ ) _lowerCAmelCase : str = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) _lowerCAmelCase : int = self.get_rust_tokenizer() _lowerCAmelCase : Dict = tokenizer.encode(a__ ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) @slow def __A ( self ): _lowerCAmelCase : int = """Hello World!""" _lowerCAmelCase : Optional[int] = [2, 31227, 4447, 35] self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): _lowerCAmelCase : Any = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _lowerCAmelCase : List[str] = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) ) @slow def __A ( self ): # fmt: off _lowerCAmelCase : List[str] = { """input_ids""": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="""facebook/xglm-564M""" , padding=a__ , )
44
def A_ ( _lowerCAmelCase = 50 ) -> int: UpperCamelCase : List[Any] = [[0] * 3 for _ in range(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 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
52
0
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): debug_launcher(test_script.main ) def __UpperCAmelCase ( self ): debug_launcher(test_ops.main )
45
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def A_ ( _lowerCAmelCase ) -> dict[str, str]: UpperCamelCase : Optional[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key UpperCamelCase : Tuple = remove_duplicates(key.upper() ) UpperCamelCase : int = len(_lowerCAmelCase ) # First fill cipher with key characters UpperCamelCase : int = {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_lowerCAmelCase ) , 26 ): UpperCamelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase : List[str] = alphabet[i - offset] UpperCamelCase : List[Any] = char return cipher_alphabet def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: return "".join(cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( ) -> None: UpperCamelCase : int = input("Enter message to encode or decode: " ).strip() UpperCamelCase : str = input("Enter keyword: " ).strip() UpperCamelCase : Union[str, Any] = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: UpperCamelCase : List[str] = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) UpperCamelCase : str = create_cipher_map(_lowerCAmelCase ) print(func(_lowerCAmelCase , _lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
52
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ["GLPNFeatureExtractor"] SCREAMING_SNAKE_CASE__ = ["GLPNImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
46
from sklearn.metrics import fa_score import datasets __lowerCamelCase : List[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCamelCase : List[Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCamelCase : str = """ @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 ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def __UpperCamelCase( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ): '''simple docstring''' UpperCamelCase : List[str] = fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
52
0
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A__ : @staticmethod def A ( *_a : Optional[Any] , **_a : int ) -> Union[str, Any]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_torch class A__ ( unittest.TestCase ): A__ = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def A ( self : Tuple , _a : Union[str, Any] , _a : Optional[int] , _a : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline( 'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' ) _SCREAMING_SNAKE_CASE =[ { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'candidate_labels': ['cat', 'remote', 'couch'], } ] return object_detector, examples def A ( self : List[str] , _a : Any , _a : Tuple ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =object_detector(examples[0] , threshold=0.0 ) _SCREAMING_SNAKE_CASE =len(_a ) self.assertGreater(_a , 0 ) self.assertEqual( _a , [ { 'score': ANY(_a ), 'label': ANY(_a ), 'box': {'xmin': ANY(_a ), 'ymin': ANY(_a ), 'xmax': ANY(_a ), 'ymax': ANY(_a )}, } for i in range(_a ) ] , ) @require_tf @unittest.skip('Zero Shot Object Detection not implemented in TF' ) def A ( self : Any ) -> Tuple: '''simple docstring''' pass @require_torch def A ( self : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline( 'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( './tests/fixtures/tests_samples/COCO/000000039769.png' , candidate_labels=['cat', 'remote', 'couch'] , threshold=0.64 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, {'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}}, {'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, ] , ) _SCREAMING_SNAKE_CASE =object_detector( [ { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'candidate_labels': ['cat', 'remote', 'couch'], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, {'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}}, {'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, ] ] , ) @require_torch @slow def A ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ] , ) _SCREAMING_SNAKE_CASE =object_detector( [ { 'image': 'http://images.cocodataset.org/val2017/000000039769.jpg', 'candidate_labels': ['cat', 'remote', 'couch'], }, { 'image': 'http://images.cocodataset.org/val2017/000000039769.jpg', 'candidate_labels': ['cat', 'remote', 'couch'], }, ] , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ], [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ], ] , ) @require_tf @unittest.skip('Zero Shot Object Detection not implemented in TF' ) def A ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass @require_torch @slow def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =0.2 _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , threshold=_a , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, ] , ) @require_torch @slow def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =2 _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , top_k=_a , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, ] , )
47
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = KandinskyInpaintPipeline _UpperCAmelCase :List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] _UpperCAmelCase :Dict = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] _UpperCAmelCase :Optional[int] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _UpperCAmelCase :int = False @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCamelCase( self ): '''simple docstring''' return 100 @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : Optional[int] = MultilingualCLIP(A_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase : List[Any] = UNetaDConditionModel(**A_ ) return model @property def __UpperCamelCase( self ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.dummy_text_encoder UpperCamelCase : str = self.dummy_tokenizer UpperCamelCase : List[Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="epsilon" , thresholding=A_ , ) UpperCamelCase : Optional[Any] = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __UpperCamelCase( self , A_ , A_=0 ): '''simple docstring''' UpperCamelCase : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image UpperCamelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(A_ ) ).convert("RGB" ).resize((256, 256) ) # create mask UpperCamelCase : str = np.ones((64, 64) , dtype=np.floataa ) UpperCamelCase : str = 0 if str(A_ ).startswith("mps" ): UpperCamelCase : int = torch.manual_seed(A_ ) else: UpperCamelCase : Tuple = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase : Union[str, Any] = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = "cpu" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**A_ ) UpperCamelCase : Tuple = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase : List[Any] = output.images UpperCamelCase : List[Any] = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase : List[Any] = image[0, -3:, -3:, -1] UpperCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) UpperCamelCase : Union[str, Any] = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __UpperCamelCase( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) UpperCamelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) UpperCamelCase : Dict = np.ones((768, 768) , dtype=np.floataa ) UpperCamelCase : str = 0 UpperCamelCase : List[Any] = "a hat" UpperCamelCase : Tuple = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) UpperCamelCase : Optional[Any] = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[Any] = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() UpperCamelCase : Dict = pipeline( A_ , image=A_ , mask_image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
52
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Optional[Any] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right SCREAMING_SNAKE_CASE__ : str = 250004 SCREAMING_SNAKE_CASE__ : Dict = 250020 @require_sentencepiece @require_tokenizers class UpperCamelCase__ (lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : Optional[int] = MBartTokenizer lowerCamelCase_ : Dict = MBartTokenizerFast lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : str = True def _lowercase ( self ) -> int: super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase : Tuple = MBartTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self ) -> Tuple: lowerCamelCase : Union[str, Any] = MBartTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = tokenizer.tokenize("This is a test" ) self.assertListEqual(UpperCamelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase : Tuple = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase : Dict = tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase : List[str] = tokenizer.convert_ids_to_tokens(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def _lowercase ( self ) -> Union[str, Any]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase : List[str] = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : int = self.tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : str = tempfile.mkdtemp() lowerCamelCase : Dict = tokenizer_r.save_pretrained(UpperCamelCase__ ) lowerCamelCase : Optional[int] = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) lowerCamelCase : Optional[int] = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way lowerCamelCase : Optional[Any] = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=True lowerCamelCase : Union[str, Any] = tempfile.mkdtemp() lowerCamelCase : Tuple = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) lowerCamelCase : Dict = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way lowerCamelCase : Dict = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : Dict = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=False lowerCamelCase : List[Any] = tempfile.mkdtemp() lowerCamelCase : str = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) lowerCamelCase : str = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase : List[str] = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : List[str] = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : str = """facebook/mbart-large-en-ro""" lowerCamelCase_ : Tuple = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] lowerCamelCase_ : List[str] = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] lowerCamelCase_ : str = [8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2, EN_CODE] @classmethod def _lowercase ( cls ) -> List[Any]: lowerCamelCase : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) lowerCamelCase : Dict = 1 return cls def _lowercase ( self ) -> Optional[Any]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_0020 ) def _lowercase ( self ) -> List[str]: lowerCamelCase : str = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCamelCase__ ) def _lowercase ( self ) -> Tuple: self.assertIn(UpperCamelCase__ , self.tokenizer.all_special_ids ) lowerCamelCase : List[Any] = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] lowerCamelCase : Optional[Any] = self.tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) lowerCamelCase : Tuple = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCamelCase__ ) def _lowercase ( self ) -> Union[str, Any]: lowerCamelCase : Any = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = 10 lowerCamelCase : List[str] = self.tokenizer(UpperCamelCase__ , max_length=UpperCamelCase__ , truncation=UpperCamelCase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , UpperCamelCase__ ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) def _lowercase ( self ) -> int: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_0026, 25_0001] ) def _lowercase ( self ) -> Optional[int]: lowerCamelCase : Tuple = tempfile.mkdtemp() lowerCamelCase : Union[str, Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(UpperCamelCase__ ) lowerCamelCase : int = MBartTokenizer.from_pretrained(UpperCamelCase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCamelCase__ ) @require_torch def _lowercase ( self ) -> Tuple: lowerCamelCase : Dict = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCamelCase__ , return_tensors="pt" ) lowerCamelCase : str = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def _lowercase ( self ) -> List[Any]: lowerCamelCase : Optional[Any] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) lowerCamelCase : Optional[int] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase : str = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , UpperCamelCase__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : int = self.tokenizer(self.src_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=3 , return_tensors="pt" ) lowerCamelCase : List[str] = self.tokenizer( text_target=self.tgt_text , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=10 , return_tensors="pt" ) lowerCamelCase : Tuple = targets["input_ids"] lowerCamelCase : List[Any] = shift_tokens_right(UpperCamelCase__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _lowercase ( self ) -> Union[str, Any]: lowerCamelCase : Union[str, Any] = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , { # A, test, EOS, en_XX "input_ids": [[62, 3034, 2, 25_0004]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_0001, } , )
48
class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = set_counts UpperCamelCase : int = max(A_ ) UpperCamelCase : Optional[Any] = len(A_ ) UpperCamelCase : Union[str, Any] = [1] * num_sets UpperCamelCase : Union[str, Any] = list(range(A_ ) ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = self.get_parent(A_ ) UpperCamelCase : Optional[int] = self.get_parent(A_ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] UpperCamelCase : int = 0 UpperCamelCase : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 UpperCamelCase : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] UpperCamelCase : Any = 0 UpperCamelCase : Optional[int] = src_parent UpperCamelCase : int = self.set_counts[src_parent] UpperCamelCase : Any = max(self.max_set , A_ ) return True def __UpperCamelCase( self , A_ ): '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set UpperCamelCase : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
52
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __snake_case :Optional[int] = '''src/diffusers''' __snake_case :Any = '''.''' # This is to make sure the diffusers module imported is the one in the repo. __snake_case :List[Any] = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) __snake_case :int = spec.loader.load_module() def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): return line.startswith(_UpperCAmelCase ) or len(_UpperCAmelCase ) <= 1 or re.search(R'''^\s*\)(\s*->.*:|:)\s*$''' , _UpperCAmelCase ) is not None def __snake_case ( _UpperCAmelCase ): __a = object_name.split('''.''' ) __a = 0 # First let's find the module where our object lives. __a = parts[i] while i < len(_UpperCAmelCase ) and not os.path.isfile(os.path.join(_UpperCAmelCase , f'{module}.py' ) ): i += 1 if i < len(_UpperCAmelCase ): __a = os.path.join(_UpperCAmelCase , parts[i] ) if i >= len(_UpperCAmelCase ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(_UpperCAmelCase , f'{module}.py' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a = f.readlines() # Now let's find the class / func in the code! __a = '''''' __a = 0 for name in parts[i + 1 :]: while ( line_index < len(_UpperCAmelCase ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(_UpperCAmelCase ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __a = line_index while line_index < len(_UpperCAmelCase ) and _should_continue(lines[line_index] , _UpperCAmelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __a = lines[start_index:line_index] return "".join(_UpperCAmelCase ) __snake_case :List[Any] = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') __snake_case :Tuple = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') __snake_case :Union[str, Any] = re.compile(r'''<FILL\s+[^>]*>''') def __snake_case ( _UpperCAmelCase ): __a = code.split('''\n''' ) __a = 0 while idx < len(_UpperCAmelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(_UpperCAmelCase ): return re.search(R'''^(\s*)\S''' , lines[idx] ).groups()[0] return "" def __snake_case ( _UpperCAmelCase ): __a = len(get_indent(_UpperCAmelCase ) ) > 0 if has_indent: __a = f'class Bla:\n{code}' __a = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=_UpperCAmelCase ) __a = black.format_str(_UpperCAmelCase , mode=_UpperCAmelCase ) __a , __a = style_docstrings_in_code(_UpperCAmelCase ) return result[len('''class Bla:\n''' ) :] if has_indent else result def __snake_case ( _UpperCAmelCase , _UpperCAmelCase=False ): with open(_UpperCAmelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a = f.readlines() __a = [] __a = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(_UpperCAmelCase ): __a = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __a , __a , __a = search.groups() __a = find_code_in_diffusers(_UpperCAmelCase ) __a = get_indent(_UpperCAmelCase ) __a = line_index + 1 if indent == theoretical_indent else line_index + 2 __a = theoretical_indent __a = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __a = True while line_index < len(_UpperCAmelCase ) and should_continue: line_index += 1 if line_index >= len(_UpperCAmelCase ): break __a = lines[line_index] __a = _should_continue(_UpperCAmelCase , _UpperCAmelCase ) and re.search(f'^{indent}# End copy' , _UpperCAmelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __a = lines[start_index:line_index] __a = ''''''.join(_UpperCAmelCase ) # Remove any nested `Copied from` comments to avoid circular copies __a = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(_UpperCAmelCase ) is None] __a = '''\n'''.join(_UpperCAmelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(_UpperCAmelCase ) > 0: __a = replace_pattern.replace('''with''' , '''''' ).split(''',''' ) __a = [_re_replace_pattern.search(_UpperCAmelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue __a , __a , __a = pattern.groups() __a = re.sub(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if option.strip() == "all-casing": __a = re.sub(obja.lower() , obja.lower() , _UpperCAmelCase ) __a = re.sub(obja.upper() , obja.upper() , _UpperCAmelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __a = blackify(lines[start_index - 1] + theoretical_code ) __a = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __a = lines[:start_index] + [theoretical_code] + lines[line_index:] __a = start_index + 1 if overwrite and len(_UpperCAmelCase ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(_UpperCAmelCase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(_UpperCAmelCase ) return diffs def __snake_case ( _UpperCAmelCase = False ): __a = glob.glob(os.path.join(_UpperCAmelCase , '''**/*.py''' ) , recursive=_UpperCAmelCase ) __a = [] for filename in all_files: __a = is_copy_consistent(_UpperCAmelCase , _UpperCAmelCase ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(_UpperCAmelCase ) > 0: __a = '''\n'''.join(_UpperCAmelCase ) raise Exception( '''Found the following copy inconsistencies:\n''' + diff + '''\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.''' ) if __name__ == "__main__": __snake_case :List[str] = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __snake_case :int = parser.parse_args() check_copies(args.fix_and_overwrite)
49
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Any = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
from string import ascii_uppercase _UpperCAmelCase : List[str] = {str(ord(c) - 55): c for c in ascii_uppercase} def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> str: if isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('int() can\'t convert non-string with explicit base' ) if num < 0: raise ValueError('parameter must be positive int' ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if base in (0, 1): raise ValueError('base must be >= 2' ) if base > 36: raise ValueError('base must be <= 36' ) lowerCamelCase__ : Optional[Any] = '' lowerCamelCase__ : List[str] = 0 lowerCamelCase__ : Dict = 0 while div != 1: lowerCamelCase__ , lowerCamelCase__ : List[str] = divmod(_UpperCAmelCase , _UpperCAmelCase ) if base >= 11 and 9 < mod < 36: lowerCamelCase__ : Dict = ALPHABET_VALUES[str(_UpperCAmelCase )] else: lowerCamelCase__ : int = str(_UpperCAmelCase ) new_value += actual_value lowerCamelCase__ : List[Any] = num // base lowerCamelCase__ : Optional[int] = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(_UpperCAmelCase ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(10_00): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
50
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class A__ ( __snake_case , __snake_case ): _UpperCAmelCase :Optional[int] = 'convnextv2' def __init__( self , A_=3 , A_=4 , A_=4 , A_=None , A_=None , A_="gelu" , A_=0.02 , A_=1e-12 , A_=0.0 , A_=224 , A_=None , A_=None , **A_ , ): '''simple docstring''' super().__init__(**A_ ) UpperCamelCase : Dict = num_channels UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Union[str, Any] = num_stages UpperCamelCase : List[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCamelCase : List[str] = [3, 3, 9, 3] if depths is None else depths UpperCamelCase : Dict = hidden_act UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : str = drop_path_rate UpperCamelCase : List[str] = image_size UpperCamelCase : List[str] = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase : str = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
52
0
def A (__A : list[int] , __A : int ) -> bool: """simple docstring""" UpperCAmelCase_ = len(__A ) UpperCAmelCase_ = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): UpperCAmelCase_ = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): UpperCAmelCase_ = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: UpperCAmelCase_ = subset[i - 1][j] if arr[i - 1] <= j: UpperCAmelCase_ = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
51
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_lowerCAmelCase ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def A_ ( ) -> Tuple: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def A_ ( ) -> Optional[int]: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_lowerCAmelCase ): http_head("https://huggingface.co" )
52
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class snake_case : """simple docstring""" SCREAMING_SNAKE_CASE_ : str =field( metadata={"help": "The output directory where the model will be written."} , ) SCREAMING_SNAKE_CASE_ : str =field( metadata={ "help": ( "The encoder model checkpoint for weights initialization." "Don't set if you want to train an encoder model from scratch." ) } , ) SCREAMING_SNAKE_CASE_ : str =field( metadata={ "help": ( "The decoder model checkpoint for weights initialization." "Don't set if you want to train a decoder model from scratch." ) } , ) SCREAMING_SNAKE_CASE_ : Optional[str] =field( default=__lowerCamelCase , metadata={"help": "Pretrained encoder config name or path if not the same as encoder_model_name"} ) SCREAMING_SNAKE_CASE_ : Optional[str] =field( default=__lowerCamelCase , metadata={"help": "Pretrained decoder config name or path if not the same as decoder_model_name"} ) def lowercase__ ( ) -> Any: """simple docstring""" __UpperCamelCase = HfArgumentParser((ModelArguments,) ) ((__UpperCamelCase) , ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: __UpperCamelCase = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: __UpperCamelCase = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: __UpperCamelCase = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: __UpperCamelCase = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=__lowercase , decoder_config=__lowercase , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens __UpperCamelCase = decoder_config.decoder_start_token_id __UpperCamelCase = decoder_config.pad_token_id if decoder_start_token_id is None: __UpperCamelCase = decoder_config.bos_token_id if pad_token_id is None: __UpperCamelCase = decoder_config.eos_token_id # This is necessary to make Flax's generate() work __UpperCamelCase = decoder_config.eos_token_id __UpperCamelCase = decoder_start_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) __UpperCamelCase = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) __UpperCamelCase = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
53
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase__ (lowerCAmelCase_ = 100_0000 , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = defaultdict(lowerCAmelCase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowerCAmelCase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"{solution() = }")
54
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCamelCase : List[Any] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ __lowerCamelCase : Optional[int] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ __lowerCamelCase : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def A_ ( _lowerCAmelCase ) -> str: def remove_articles(_lowerCAmelCase ): UpperCamelCase : Tuple = re.compile(r"\b(a|an|the)\b" , re.UNICODE ) return re.sub(_lowerCAmelCase , " " , _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase ): UpperCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = [any(compute_exact(_lowerCAmelCase , _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 100 def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Optional[int] = Counter(_lowerCAmelCase ) UpperCamelCase : List[Any] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : Tuple = scount * numref UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Tuple = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Dict = ccount * numref # KEEP UpperCamelCase : List[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Union[str, Any] = keepgramcounter_rep & rgramcounter UpperCamelCase : Dict = sgramcounter_rep & rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Any = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Union[str, Any] = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : Any = sgramcounter_rep - cgramcounter_rep UpperCamelCase : str = delgramcounter_rep - rgramcounter UpperCamelCase : Any = sgramcounter_rep - rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Dict = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : str = deltmpscorea / len(_lowerCAmelCase ) # ADDITION UpperCamelCase : List[str] = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : List[str] = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) UpperCamelCase : Dict = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 UpperCamelCase : Tuple = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Tuple = addtmpscore / len(_lowerCAmelCase ) UpperCamelCase : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : List[str] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: UpperCamelCase : int = len(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = ssent.split(" " ) UpperCamelCase : Dict = csent.split(" " ) UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Any = [] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : str = [] UpperCamelCase : str = [] UpperCamelCase : Dict = [] UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = [] for rsent in rsents: UpperCamelCase : List[Any] = rsent.split(" " ) UpperCamelCase : List[str] = [] UpperCamelCase : int = [] UpperCamelCase : Tuple = [] ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : List[Any] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : List[str] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : str = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : Union[str, Any] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Union[str, Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = "13a" , _lowerCAmelCase = True ) -> Optional[Any]: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : Dict = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : str = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: UpperCamelCase : Dict = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": UpperCamelCase : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase , escape=_lowerCAmelCase ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase ) else: UpperCamelCase : Union[str, Any] = sentence if not return_str: UpperCamelCase : Tuple = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError("Sources length must match predictions and references lengths." ) UpperCamelCase : Optional[Any] = 0 for src, pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ) , normalize(_lowerCAmelCase ) , [normalize(_lowerCAmelCase ) for sent in refs] ) UpperCamelCase : Optional[int] = sari_score / len(_lowerCAmelCase ) return 100 * sari_score def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase="exp" , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> List[str]: UpperCamelCase : Optional[Any] = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] UpperCamelCase : Tuple = sacrebleu.corpus_bleu( _lowerCAmelCase , _lowerCAmelCase , smooth_method=_lowerCAmelCase , smooth_value=_lowerCAmelCase , force=_lowerCAmelCase , lowercase=_lowerCAmelCase , use_effective_order=_lowerCAmelCase , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = {} result.update({"sari": compute_sari(sources=A_ , predictions=A_ , references=A_ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A_ , references=A_ )} ) result.update({"exact": compute_em(predictions=A_ , references=A_ )} ) return result
52
0
'''simple docstring''' def __snake_case ( UpperCAmelCase_ : int = 1000 ): return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
55
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : str = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = 'roberta' def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Any = type_vocab_size UpperCamelCase : int = initializer_range UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = position_embedding_type UpperCamelCase : Any = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
52
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a : Optional[int] = logging.get_logger(__name__) a : Dict = { 'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json', 'Salesforce/blip-vqa-capfit-large': ( 'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-base': ( 'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-large': ( 'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json' ), 'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json', 'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json', 'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json', 'Salesforce/blip-itm-large-flikr': ( 'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json' ), } class a ( _lowerCamelCase ): snake_case_ = "blip_text_model" def __init__( self : Dict , lowercase_ : Tuple=3_0524 , lowercase_ : Any=768 , lowercase_ : Optional[Any]=768 , lowercase_ : int=3072 , lowercase_ : Tuple=768 , lowercase_ : List[Any]=12 , lowercase_ : Union[str, Any]=8 , lowercase_ : Optional[Any]=512 , lowercase_ : Optional[int]="gelu" , lowercase_ : int=1e-12 , lowercase_ : Union[str, Any]=0.0 , lowercase_ : str=0.0 , lowercase_ : int=0.02 , lowercase_ : int=3_0522 , lowercase_ : Any=2 , lowercase_ : Any=0 , lowercase_ : int=102 , lowercase_ : List[Any]=True , lowercase_ : Optional[int]=True , **lowercase_ : Optional[int] , ): super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , sep_token_id=lowercase_ , **lowercase_ , ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = encoder_hidden_size snake_case_ = intermediate_size snake_case_ = projection_dim snake_case_ = hidden_dropout_prob snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = attention_probs_dropout_prob snake_case_ = is_decoder snake_case_ = use_cache @classmethod def A_ ( cls : str , lowercase_ : Union[str, os.PathLike] , **lowercase_ : int ): cls._set_token_in_kwargs(lowercase_ ) snake_case_ ,snake_case_ = cls.get_config_dict(lowercase_ , **lowercase_ ) # get the text config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": snake_case_ = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(lowercase_ , **lowercase_ ) class a ( _lowerCamelCase ): snake_case_ = "blip_vision_model" def __init__( self : int , lowercase_ : Dict=768 , lowercase_ : Tuple=3072 , lowercase_ : Optional[Any]=512 , lowercase_ : Union[str, Any]=12 , lowercase_ : Optional[Any]=12 , lowercase_ : Any=384 , lowercase_ : str=16 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : Tuple=1e-5 , lowercase_ : Optional[int]=0.0 , lowercase_ : Optional[int]=1e-10 , **lowercase_ : Optional[Any] , ): super().__init__(**lowercase_ ) snake_case_ = hidden_size snake_case_ = intermediate_size snake_case_ = projection_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = patch_size snake_case_ = image_size snake_case_ = initializer_range snake_case_ = attention_dropout snake_case_ = layer_norm_eps snake_case_ = hidden_act @classmethod def A_ ( cls : Optional[Any] , lowercase_ : Union[str, os.PathLike] , **lowercase_ : int ): cls._set_token_in_kwargs(lowercase_ ) snake_case_ ,snake_case_ = cls.get_config_dict(lowercase_ , **lowercase_ ) # get the vision config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": snake_case_ = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(lowercase_ , **lowercase_ ) class a ( _lowerCamelCase ): snake_case_ = "blip" snake_case_ = True def __init__( self : str , lowercase_ : str=None , lowercase_ : List[str]=None , lowercase_ : List[str]=512 , lowercase_ : int=2.6592 , lowercase_ : List[Any]=256 , **lowercase_ : List[str] , ): super().__init__(**lowercase_ ) if text_config is None: snake_case_ = {} logger.info('''`text_config` is `None`. Initializing the `BlipTextConfig` with default values.''' ) if vision_config is None: snake_case_ = {} logger.info('''`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.''' ) snake_case_ = BlipTextConfig(**lowercase_ ) snake_case_ = BlipVisionConfig(**lowercase_ ) snake_case_ = self.vision_config.hidden_size snake_case_ = projection_dim snake_case_ = logit_scale_init_value snake_case_ = 1.0 snake_case_ = 0.02 snake_case_ = image_text_hidden_size @classmethod def A_ ( cls : int , lowercase_ : BlipTextConfig , lowercase_ : BlipVisionConfig , **lowercase_ : List[str] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowercase_ ) def A_ ( self : str ): snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.text_config.to_dict() snake_case_ = self.vision_config.to_dict() snake_case_ = self.__class__.model_type return output
56
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_case ): def __init__( self , A_ , A_ ): '''simple docstring''' super().__init__() self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = 100 , A_ = None , A_ = None , A_ = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCamelCase : str = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) UpperCamelCase : Union[str, Any] = int(A_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : List[str] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) UpperCamelCase : Any = int(A_ ) UpperCamelCase : Union[str, Any] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : Optional[int] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(A_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) UpperCamelCase : Optional[Any] = randn_tensor(A_ , generator=A_ , device=self.device , dtype=A_ ) # set step values self.scheduler.set_timesteps(A_ , device=audio.device ) UpperCamelCase : Optional[int] = self.scheduler.timesteps.to(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(A_ , A_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : int = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase : Optional[Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A_ )
52
0
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
import functools def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: UpperCamelCase : Optional[int] = len(_lowerCAmelCase ) UpperCamelCase : List[str] = len(_lowerCAmelCase ) @functools.cache def min_distance(_lowerCAmelCase , _lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa UpperCamelCase : Union[str, Any] = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _lowerCAmelCase ) , 1 + min_distance(_lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
52
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 lowercase_ = None lowercase_ = """<""" 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 lowercase_ = [ 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 a_ : '''simple docstring''' UpperCamelCase = True UpperCamelCase = None # Automatically constructed UpperCamelCase = "PIL.Image.Image" UpperCamelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCamelCase = field(default='''Image''' , init=snake_case_ , repr=snake_case_ ) def __call__( self ) -> Tuple: return self.pa_type def snake_case_( self , A ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(A , A ): _SCREAMING_SNAKE_CASE = np.array(A ) if isinstance(A , A ): return {"path": value, "bytes": None} elif isinstance(A , A ): return {"path": None, "bytes": value} elif isinstance(A , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(A ) elif isinstance(A , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(A ) 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 snake_case_( self , A , A=None ) -> "PIL.Image.Image": 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: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 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(A ): _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) else: _SCREAMING_SNAKE_CASE = path.split("""::""" )[-1] try: _SCREAMING_SNAKE_CASE = string_to_dict(A , config.HUB_DATASETS_URL )["""repo_id"""] _SCREAMING_SNAKE_CASE = token_per_repo_id.get(A ) except ValueError: _SCREAMING_SNAKE_CASE = None with xopen(A , """rb""" , use_auth_token=A ) as f: _SCREAMING_SNAKE_CASE = BytesIO(f.read() ) _SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: _SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case_( self , A ) -> pa.StructArray: if pa.types.is_string(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = 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: _SCREAMING_SNAKE_CASE = storage.field("""bytes""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""path""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(A ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def snake_case_( self , A ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(A ): with xopen(A , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() return bytes_ _SCREAMING_SNAKE_CASE = 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() , ) _SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(A ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def lowerCamelCase ( ) ->List[str]: 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() _SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->bytes: _SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): _SCREAMING_SNAKE_CASE = image.format else: _SCREAMING_SNAKE_CASE = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->dict: if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : np.ndarray ) ->dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) _SCREAMING_SNAKE_CASE = array.dtype _SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER _SCREAMING_SNAKE_CASE = dtype.kind _SCREAMING_SNAKE_CASE = dtype.itemsize _SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _SCREAMING_SNAKE_CASE = 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: _SCREAMING_SNAKE_CASE = 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: _SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.dtype(__lowerCamelCase ) 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}' ) _SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) ->List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
58
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __lowerCamelCase : str = random.Random() if is_torch_available(): import torch def A_ ( _lowerCAmelCase , _lowerCAmelCase=1.0 , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: if rng is None: UpperCamelCase : Optional[int] = global_rng UpperCamelCase : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class A__ ( unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ): '''simple docstring''' UpperCamelCase : Tuple = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Union[str, Any] = feature_size UpperCamelCase : List[str] = padding_value UpperCamelCase : Optional[Any] = sampling_rate UpperCamelCase : List[str] = return_attention_mask UpperCamelCase : List[Any] = do_normalize def __UpperCamelCase( self ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCamelCase( self , A_=False , A_=False ): '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: UpperCamelCase : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Dict = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Union[str, Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = ASTFeatureExtractor def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = ASTFeatureExtractionTester(self ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Dict = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCamelCase : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(A_ ) UpperCamelCase : Any = feat_extract(A_ , return_tensors="np" ).input_values UpperCamelCase : List[str] = feat_extract(A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) @require_torch def __UpperCamelCase( self ): '''simple docstring''' import torch UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : str = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __UpperCamelCase( self , A_ ): '''simple docstring''' from datasets import load_dataset UpperCamelCase : Dict = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech UpperCamelCase : Any = ds.sort("id" ).select(range(A_ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : Tuple = ASTFeatureExtractor() UpperCamelCase : str = feature_extractor(A_ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A_ , atol=1e-4 ) )
52
0
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class UpperCAmelCase : def __init__(self : List[str] ) -> Any: '''simple docstring''' snake_case : Tuple = "" snake_case : str = "" snake_case : Dict = [] snake_case : str = 0 snake_case : Tuple = 2_56 snake_case : Optional[Any] = 0 snake_case : Union[str, Any] = 0 snake_case : Any = 0 snake_case : Union[str, Any] = 0 def _SCREAMING_SNAKE_CASE (self : List[Any] , snake_case__ : Tuple ) -> List[Any]: '''simple docstring''' snake_case : Optional[Any] = cva.imread(snake_case__ , 0 ) snake_case : Union[str, Any] = copy.deepcopy(self.img ) snake_case , snake_case , snake_case : Tuple = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label="x" ) snake_case : Any = np.sum(snake_case__ ) for i in range(len(snake_case__ ) ): snake_case : Union[str, Any] = x[i] / self.k self.sk += prk snake_case : Optional[Any] = (self.L - 1) * self.sk if self.rem != 0: snake_case : List[str] = int(last % last ) snake_case : List[str] = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(snake_case__ ) snake_case : int = int(np.ma.count(self.img ) / self.img[1].size ) snake_case : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): snake_case : Union[str, Any] = self.img[j][i] if num != self.last_list[num]: snake_case : Dict = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> List[Any]: '''simple docstring''' plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def _SCREAMING_SNAKE_CASE (self : str ) -> int: '''simple docstring''' cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": __lowerCamelCase = os.path.join(os.path.basename(__file__), """image_data/input.jpg""") __lowerCamelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
59
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ): '''simple docstring''' UpperCamelCase : int = bp_numa UpperCamelCase : int = bp_numa UpperCamelCase : List[Any] = bp_numa UpperCamelCase : Optional[int] = conva_get[:2] UpperCamelCase : Optional[Any] = conva_get[2] UpperCamelCase : Dict = size_pa UpperCamelCase : Union[str, Any] = rate_w UpperCamelCase : Dict = rate_t UpperCamelCase : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] UpperCamelCase : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : Optional[Any] = -2 * np.random.rand(self.conva[1] ) + 1 UpperCamelCase : Any = -2 * np.random.rand(self.num_bpa ) + 1 UpperCamelCase : int = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(A_ , "wb" ) as f: pickle.dump(A_ , A_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __UpperCamelCase( cls , A_ ): '''simple docstring''' with open(A_ , "rb" ) as f: UpperCamelCase : Optional[Any] = pickle.load(A_ ) # noqa: S301 UpperCamelCase : List[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) UpperCamelCase : Union[str, Any] = model_dic.get("size_pooling1" ) UpperCamelCase : List[Any] = model_dic.get("num_bp1" ) UpperCamelCase : Dict = model_dic.get("num_bp2" ) UpperCamelCase : Dict = model_dic.get("num_bp3" ) UpperCamelCase : Dict = model_dic.get("rate_weight" ) UpperCamelCase : str = model_dic.get("rate_thre" ) # create model instance UpperCamelCase : Any = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter UpperCamelCase : str = model_dic.get("w_conv1" ) UpperCamelCase : Optional[Any] = model_dic.get("wkj" ) UpperCamelCase : int = model_dic.get("vji" ) UpperCamelCase : Any = model_dic.get("thre_conv1" ) UpperCamelCase : Optional[int] = model_dic.get("thre_bp2" ) UpperCamelCase : Union[str, Any] = model_dic.get("thre_bp3" ) return conv_ins def __UpperCamelCase( self , A_ ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def __UpperCamelCase( self , A_ ): '''simple docstring''' return round(A_ , 3 ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = convs[0] UpperCamelCase : Optional[Any] = convs[1] UpperCamelCase : Optional[Any] = np.shape(A_ )[0] # get the data slice of original image data, data_focus UpperCamelCase : List[str] = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): UpperCamelCase : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): UpperCamelCase : str = [] for i_focus in range(len(A_ ) ): UpperCamelCase : List[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) UpperCamelCase : Optional[int] = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion UpperCamelCase : List[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) UpperCamelCase : Tuple = np.asarray(A_ ) return focus_list, data_featuremap def __UpperCamelCase( self , A_ , A_ , A_="average_pool" ): '''simple docstring''' UpperCamelCase : Any = len(featuremaps[0] ) UpperCamelCase : str = int(size_map / size_pooling ) UpperCamelCase : Optional[int] = [] for i_map in range(len(A_ ) ): UpperCamelCase : Tuple = featuremaps[i_map] UpperCamelCase : Any = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): UpperCamelCase : int = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) UpperCamelCase : Optional[Any] = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = [] for i in range(len(A_ ) ): UpperCamelCase : List[Any] = np.shape(data[i] ) UpperCamelCase : str = data[i].reshape(1 , shapes[0] * shapes[1] ) UpperCamelCase : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) UpperCamelCase : Any = np.asarray(A_ ) return data_expanded def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = np.asarray(A_ ) UpperCamelCase : List[Any] = np.shape(A_ ) UpperCamelCase : Any = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[int] = 0 for i_map in range(A_ ): UpperCamelCase : int = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): UpperCamelCase : str = pd_pool[ i_pool ] UpperCamelCase : str = i_pool + 1 UpperCamelCase : str = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=bool ): '''simple docstring''' print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(A_ )) ) print((" - - Shape: Teach_Data ", np.shape(A_ )) ) UpperCamelCase : List[str] = 0 UpperCamelCase : Union[str, Any] = [] UpperCamelCase : int = 1_0000 while rp < n_repeat and mse >= error_accuracy: UpperCamelCase : Tuple = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) UpperCamelCase : Any = np.asmatrix(datas_train[p] ) UpperCamelCase : List[str] = np.asarray(datas_teach[p] ) UpperCamelCase , UpperCamelCase : Dict = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : Tuple = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : int = np.shape(A_ ) UpperCamelCase : List[str] = self._expand(A_ ) UpperCamelCase : Optional[int] = data_bp_input UpperCamelCase : str = np.dot(A_ , self.vji.T ) - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) UpperCamelCase : List[Any] = np.dot(A_ , self.wkj.T ) - self.thre_bpa UpperCamelCase : Dict = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- UpperCamelCase : List[Any] = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : str = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : Any = np.dot(A_ , self.vji ) UpperCamelCase : Dict = pd_i_all / (self.size_poolinga * self.size_poolinga) UpperCamelCase : List[Any] = pd_conva_pooled.T.getA().tolist() UpperCamelCase : List[Any] = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): UpperCamelCase : List[Any] = self._expand_mat(pd_conva_all[k_conv] ) UpperCamelCase : List[Any] = self.rate_weight * np.dot(A_ , A_ ) UpperCamelCase : str = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) UpperCamelCase : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer UpperCamelCase : Optional[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight UpperCamelCase : List[Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight UpperCamelCase : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre UpperCamelCase : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image UpperCamelCase : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) UpperCamelCase : Any = rp + 1 UpperCamelCase : Union[str, Any] = error_count / patterns all_mse.append(A_ ) def draw_error(): UpperCamelCase : Tuple = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , "+-" ) plt.plot(A_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(A_ )) ) for p in range(len(A_ ) ): UpperCamelCase : int = np.asmatrix(datas_test[p] ) UpperCamelCase , UpperCamelCase : Any = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : List[str] = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : Dict = self._expand(A_ ) UpperCamelCase : List[Any] = data_bp_input UpperCamelCase : Any = bp_outa * self.vji.T - self.thre_bpa UpperCamelCase : List[Any] = self.sig(A_ ) UpperCamelCase : int = bp_outa * self.wkj.T - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) UpperCamelCase : List[str] = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = np.asmatrix(A_ ) UpperCamelCase , UpperCamelCase : List[Any] = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : str = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
52
0
"""simple docstring""" import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP snake_case__ : Dict = False try: snake_case__ : Any = _is_package_available('''google.colab''') except ModuleNotFoundError: pass @input.register class snake_case_: def __init__( self : List[Any] , UpperCamelCase_ : str = None , UpperCamelCase_ : list = [] ): lowerCAmelCase : Union[str, Any] = 0 lowerCAmelCase : str = choices lowerCAmelCase : Any = prompt if sys.platform == "win32": lowerCAmelCase : Optional[Any] = '''*''' else: lowerCAmelCase : List[str] = '''➔ ''' def lowerCamelCase__ ( self : int , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 3_2 , UpperCamelCase_ ) else: forceWrite(self.choices[index] , UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int ): if index == self.position: forceWrite(F''' {self.arrow_char} ''' ) self.write_choice(UpperCamelCase_ ) else: forceWrite(F''' {self.choices[index]}''' ) reset_cursor() def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Direction , UpperCamelCase_ : int = 1 ): lowerCAmelCase : Optional[int] = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(UpperCamelCase_ ) move_cursor(UpperCamelCase_ , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['''up'''] ) def lowerCamelCase__ ( self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['''down'''] ) def lowerCamelCase__ ( self : List[Any] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['''newline'''] ) def lowerCamelCase__ ( self : List[str] ): move_cursor(len(self.choices ) - self.position , '''DOWN''' ) return self.position @input.mark(KEYMAP['''interrupt'''] ) def lowerCamelCase__ ( self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , '''DOWN''' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(UpperCamelCase_ )] for number in range(1_0 )] ) def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : List[Any] = int(chr(self.current_selection ) ) lowerCAmelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , UpperCamelCase_ ) else: return else: return def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '''\n''' ) if in_colab: forceWrite('''Please input a choice index (starting from 0), and press enter''' , '''\n''' ) else: forceWrite('''Please select a choice using the arrow or number keys, and selecting with enter''' , '''\n''' ) lowerCAmelCase : Tuple = default_choice for i in range(len(self.choices ) ): self.print_choice(UpperCamelCase_ ) forceWrite('''\n''' ) move_cursor(len(self.choices ) - self.position , '''UP''' ) with cursor.hide(): while True: if in_colab: try: lowerCAmelCase : List[str] = int(builtins.input() ) except ValueError: lowerCAmelCase : Optional[int] = default_choice else: lowerCAmelCase : Tuple = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , '''UP''' ) clear_line() self.write_choice(UpperCamelCase_ , '''\n''' ) return choice
60
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Any = { """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""", # See all BART models at https://huggingface.co/models?filter=bart } class A__ ( __snake_case ): _UpperCAmelCase :Dict = 'bart' _UpperCAmelCase :str = ['past_key_values'] _UpperCAmelCase :Any = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , A_=5_0265 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=3 , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , **A_ , ): '''simple docstring''' UpperCamelCase : int = vocab_size UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Any = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = encoder_attention_heads UpperCamelCase : Optional[int] = decoder_ffn_dim UpperCamelCase : List[str] = decoder_layers UpperCamelCase : Optional[int] = decoder_attention_heads UpperCamelCase : int = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Tuple = activation_dropout UpperCamelCase : Tuple = activation_function UpperCamelCase : int = init_std UpperCamelCase : List[Any] = encoder_layerdrop UpperCamelCase : List[str] = decoder_layerdrop UpperCamelCase : Dict = classifier_dropout UpperCamelCase : Optional[int] = use_cache UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , A_ ): UpperCamelCase : 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." ) class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase : List[str] = {0: "batch"} UpperCamelCase : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase : Dict = {0: "batch", 1: "decoder_sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(A_ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase : Any = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase , UpperCamelCase : Optional[int] = self.num_layers for i in range(A_ ): UpperCamelCase : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase : Optional[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Tuple = super().outputs else: UpperCamelCase : Dict = super(A_ , self ).outputs if self.use_past: UpperCamelCase , UpperCamelCase : int = self.num_layers for i in range(A_ ): UpperCamelCase : int = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Tuple = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) # Generate decoder inputs UpperCamelCase : List[Any] = seq_length if not self.use_past else 1 UpperCamelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) UpperCamelCase : Optional[int] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase : List[Any] = dict(**A_ , **A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Optional[Any] = common_inputs["input_ids"].shape UpperCamelCase : List[Any] = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase , UpperCamelCase : List[str] = self.num_attention_heads UpperCamelCase : int = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : List[Any] = decoder_seq_length + 3 UpperCamelCase : str = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase : int = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(A_ , A_ )] , dim=1 ) UpperCamelCase : int = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase , UpperCamelCase : Union[str, Any] = self.num_layers UpperCamelCase : Any = min(A_ , A_ ) UpperCamelCase : List[str] = max(A_ , A_ ) - min_num_layers UpperCamelCase : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(A_ ): common_inputs["past_key_values"].append( ( torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), ) ) # TODO: test this. UpperCamelCase : Optional[Any] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(A_ , A_ ): common_inputs["past_key_values"].append((torch.zeros(A_ ), torch.zeros(A_ )) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : int = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Union[str, Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase : Optional[Any] = seqlen + 2 UpperCamelCase , UpperCamelCase : List[Any] = self.num_layers UpperCamelCase , UpperCamelCase : Optional[int] = self.num_attention_heads UpperCamelCase : str = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : Optional[Any] = common_inputs["attention_mask"].dtype UpperCamelCase : int = torch.cat( [common_inputs["attention_mask"], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) UpperCamelCase : Optional[Any] = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(A_ ) ] return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase : Union[str, Any] = tokenizer.num_special_tokens_to_add(A_ ) UpperCamelCase : int = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase : int = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase : Dict = dict(tokenizer(A_ , return_tensors=A_ ) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) elif self.task == "causal-lm": UpperCamelCase : List[str] = self._generate_dummy_inputs_for_causal_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) else: UpperCamelCase : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) return common_inputs def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[Any] = super()._flatten_past_key_values_(A_ , A_ , A_ , A_ ) else: UpperCamelCase : Optional[Any] = super(A_ , self )._flatten_past_key_values_( A_ , A_ , A_ , A_ )
52
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _a = logging.get_logger(__name__) _a = '▁' _a = {'vocab_file': 'sentencepiece.bpe.model'} _a = { 'vocab_file': { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model' ), } } _a = { 'xlm-roberta-base': 512, 'xlm-roberta-large': 512, 'xlm-roberta-large-finetuned-conll02-dutch': 512, 'xlm-roberta-large-finetuned-conll02-spanish': 512, 'xlm-roberta-large-finetuned-conll03-english': 512, 'xlm-roberta-large-finetuned-conll03-german': 512, } class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Tuple = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self , lowercase_ , lowercase_="<s>" , lowercase_="</s>" , lowercase_="</s>" , lowercase_="<s>" , lowercase_="<unk>" , lowercase_="<pad>" , lowercase_="<mask>" , lowercase_ = None , **lowercase_ , ): """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ : Any = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else mask_token UpperCAmelCase_ : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , mask_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) UpperCAmelCase_ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowercase_ ) ) UpperCAmelCase_ : Optional[int] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token UpperCAmelCase_ : Any = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCAmelCase_ : int = 1 UpperCAmelCase_ : str = len(self.sp_model ) + self.fairseq_offset UpperCAmelCase_ : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.__dict__.copy() UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : int = self.sp_model.serialized_model_proto() return state def __setstate__( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase_ : str = {} UpperCAmelCase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_ : Dict = [self.cls_token_id] UpperCAmelCase_ : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None , lowercase_ = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_ ) if token_ids_a is None: return [1] + ([0] * len(lowercase_ )) + [1] return [1] + ([0] * len(lowercase_ )) + [1, 1] + ([0] * len(lowercase_ )) + [1] def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" UpperCAmelCase_ : Any = [self.sep_token_id] UpperCAmelCase_ : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase__ ( self ): """simple docstring""" return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCAmelCase_ : str = self.sp_model.PieceToId(lowercase_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = "".join(lowercase_ ).replace(lowercase_ , " " ).strip() return out_string def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" if not os.path.isdir(lowercase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_ , "wb" ) as fi: UpperCAmelCase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
61
from math import sqrt def A_ ( _lowerCAmelCase ) -> bool: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" UpperCamelCase : List[Any] = True # 0 and 1 are none primes. if number <= 1: UpperCamelCase : List[Any] = False for divisor in range(2 , int(round(sqrt(_lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCamelCase : Union[str, Any] = False break # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'status' must been from type bool" return status def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCamelCase : int = list(range(2 , n + 1 ) ) UpperCamelCase : Optional[int] = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_lowerCAmelCase ) ): for j in range(i + 1 , len(_lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCamelCase : Tuple = 0 # filters actual prime numbers. UpperCamelCase : str = [x for x in begin_list if x != 0] # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" UpperCamelCase : str = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(_lowerCAmelCase ): ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" UpperCamelCase : Optional[Any] = [] # this list will be returns of the function. # potential prime number factors. UpperCamelCase : Tuple = 2 UpperCamelCase : str = number if number == 0 or number == 1: ans.append(_lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_lowerCAmelCase ): while quotient != 1: if is_prime(_lowerCAmelCase ) and (quotient % factor == 0): ans.append(_lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Any = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = max(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Union[str, Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Dict = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = min(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def A_ ( _lowerCAmelCase ) -> List[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def A_ ( _lowerCAmelCase ) -> Any: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (number > 2) and is_even(_lowerCAmelCase ) ), "'number' must been an int, even and > 2" UpperCamelCase : List[str] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCamelCase : Dict = get_prime_numbers(_lowerCAmelCase ) UpperCamelCase : Tuple = len(_lowerCAmelCase ) # run variable for while-loops. UpperCamelCase : Optional[int] = 0 UpperCamelCase : int = None # exit variable. for break up the loops UpperCamelCase : Union[str, Any] = True while i < len_pn and loop: UpperCamelCase : Tuple = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCamelCase : Any = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (len(_lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Tuple = 0 while numbera != 0: UpperCamelCase : Tuple = numbera % numbera UpperCamelCase : Any = numbera UpperCamelCase : Union[str, Any] = rest # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Optional[int] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCamelCase : List[Any] = prime_factorization(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = prime_factorization(_lowerCAmelCase ) elif numbera == 1 or numbera == 1: UpperCamelCase : Optional[Any] = [] UpperCamelCase : int = [] UpperCamelCase : List[Any] = max(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 UpperCamelCase : List[str] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) UpperCamelCase : Tuple = prime_fac_a.count(_lowerCAmelCase ) for _ in range(max(_lowerCAmelCase , _lowerCAmelCase ) ): ans *= n else: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCamelCase : Any = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" UpperCamelCase : int = 0 UpperCamelCase : int = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_lowerCAmelCase ): ans += 1 # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and is_prime( _lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( is_prime(_lowerCAmelCase ) and is_prime(_lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCamelCase : str = p_number_a + 1 # jump to the next number UpperCamelCase : Dict = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(_lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ans[0] != p_number_a and ans[len(_lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def A_ ( _lowerCAmelCase ) -> List[str]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" UpperCamelCase : Dict = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(_lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def A_ ( _lowerCAmelCase ) -> int: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCamelCase : int = get_divisors(_lowerCAmelCase ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(_lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCamelCase : List[str] = gcd(abs(_lowerCAmelCase ) , abs(_lowerCAmelCase ) ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def A_ ( _lowerCAmelCase ) -> Dict: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" UpperCamelCase : str = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" UpperCamelCase : Dict = 0 UpperCamelCase : Dict = 1 UpperCamelCase : Union[str, Any] = 1 # this will be return for _ in range(n - 1 ): UpperCamelCase : Any = ans ans += fiba UpperCamelCase : str = tmp return ans
52
0
from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
62
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 : str = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCamelCase : Tuple = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCamelCase : List[str] = 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 : Optional[Any] = re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") __lowerCamelCase : List[str] = { """DecisionTransformerConfig""", """EncoderDecoderConfig""", """MusicgenConfig""", """RagConfig""", """SpeechEncoderDecoderConfig""", """TimmBackboneConfig""", """VisionEncoderDecoderConfig""", """VisionTextDualEncoderConfig""", """LlamaConfig""", } def A_ ( _lowerCAmelCase ) -> List[str]: UpperCamelCase : Optional[Any] = None # source code of `config_class` UpperCamelCase : Tuple = inspect.getsource(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = _re_checkpoint.findall(_lowerCAmelCase ) # 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 : Dict = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase : Any = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: UpperCamelCase : List[Any] = ckpt_name break return checkpoint def A_ ( ) -> List[str]: UpperCamelCase : Optional[int] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCamelCase : Union[str, Any] = get_checkpoint_from_config_class(_lowerCAmelCase ) UpperCamelCase : Optional[int] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Any = "\n".join(sorted(_lowerCAmelCase ) ) raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
52
0
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[str] , __a : List[Any] , __a : str=13 , __a : Dict=10 , __a : Tuple=3 , __a : Dict=2 , __a : Any=2 , __a : Union[str, Any]=True , __a : str=True , __a : Optional[int]=32 , __a : List[str]=5 , __a : int=4 , __a : Any=37 , __a : Optional[Any]="gelu" , __a : Optional[int]=0.1 , __a : List[str]=0.1 , __a : Tuple=10 , __a : Union[str, Any]=0.02 , __a : Union[str, Any]="divided_space_time" , __a : Dict=None , ): _a = parent _a = batch_size _a = image_size _a = num_channels _a = patch_size _a = num_frames _a = is_training _a = use_labels _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = attention_type _a = initializer_range _a = scope _a = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token _a = (image_size // patch_size) ** 2 _a = (num_frames) * self.num_patches_per_frame + 1 def UpperCamelCase__ ( self : Union[str, Any] ): _a = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.num_labels ) _a = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self : int ): _a = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) _a = self.num_labels return config def UpperCamelCase__ ( self : List[Any] , __a : str , __a : Union[str, Any] , __a : List[str] ): _a = TimesformerModel(config=__a ) model.to(__a ) model.eval() _a = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self : Any , __a : Union[str, Any] , __a : str , __a : List[Any] ): _a = TimesformerForVideoClassification(__a ) model.to(__a ) model.eval() _a = model(__a ) # verify the logits shape _a = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __a ) def UpperCamelCase__ ( self : Any ): _a = self.prepare_config_and_inputs() _a , _a , _a = config_and_inputs _a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () __a =( {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification} if is_torch_available() else {} ) __a =False __a =False __a =False __a =False def UpperCamelCase__ ( self : Dict ): _a = TimesformerModelTester(self ) _a = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def UpperCamelCase__ ( self : int , __a : List[Any] , __a : List[Any] , __a : Any=False ): _a = copy.deepcopy(__a ) if return_labels: if model_class in get_values(__a ): _a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def UpperCamelCase__ ( self : int ): self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def UpperCamelCase__ ( self : List[Any] ): pass def UpperCamelCase__ ( self : Optional[int] ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def UpperCamelCase__ ( self : Dict ): _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__a ) _a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a = [*signature.parameters.keys()] _a = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def UpperCamelCase__ ( self : List[str] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__a ) @slow def UpperCamelCase__ ( self : Tuple ): for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = TimesformerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def UpperCamelCase__ ( self : Optional[Any] ): if not self.has_attentions: pass else: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = True for model_class in self.all_model_classes: _a = self.model_tester.seq_length _a = self.model_tester.num_frames _a = True _a = False _a = True _a = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__a , __a ) ) _a = outputs.attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _a = True _a = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__a , __a ) ) _a = outputs.attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) _a = len(__a ) # Check attention is always last and order is fine _a = True _a = True _a = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + 1 , len(__a ) ) _a = outputs.attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def UpperCamelCase__ ( self : str ): def check_hidden_states_output(__a : Union[str, Any] , __a : Optional[Any] , __a : Any ): _a = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__a , __a ) ) _a = outputs.hidden_states _a = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__a ) , __a ) _a = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a = True check_hidden_states_output(__a , __a , __a ) def _lowerCamelCase ( ) -> int: _a = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) _a = np.load(lowercase ) return list(lowercase ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @cached_property def UpperCamelCase__ ( self : List[str] ): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self : str ): _a = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( __a ) _a = self.default_image_processor _a = prepare_video() _a = image_processor(video[:8] , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): _a = model(**__a ) # verify the logits _a = torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __a ) _a = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) )
63
from __future__ import annotations from functools import lru_cache from math import ceil __lowerCamelCase : str = 100 __lowerCamelCase : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __lowerCamelCase : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def A_ ( _lowerCAmelCase ) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} UpperCamelCase : set[int] = set() UpperCamelCase : int UpperCamelCase : int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A_ ( _lowerCAmelCase = 5000 ) -> int | None: for number_to_partition in range(1 , _lowerCAmelCase ): if len(partition(_lowerCAmelCase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
52
0
"""simple docstring""" import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class lowercase: '''simple docstring''' def __init__( self: List[Any], a_: Optional[Any], a_: List[Any]=13, a_: List[Any]=7, a_: Tuple=False, a_: str=True, a_: str=False, a_: List[str]=True, a_: Dict=33, a_: Any=32, a_: Tuple=5, a_: List[Any]=4, a_: Any=37, a_: str="gelu", a_: Tuple=0.1, a_: Union[str, Any]=0.1, a_: Dict=512, a_: str=16, a_: str=2, a_: Tuple=0.02, a_: Optional[int]=3, a_: str=4, a_: Any=None, ): '''simple docstring''' _snake_case : Optional[Any] = parent _snake_case : Optional[Any] = batch_size _snake_case : int = seq_length _snake_case : Optional[int] = is_training _snake_case : List[str] = use_input_mask _snake_case : List[Any] = use_token_type_ids _snake_case : Any = use_labels _snake_case : List[Any] = vocab_size _snake_case : Any = hidden_size _snake_case : int = num_hidden_layers _snake_case : str = num_attention_heads _snake_case : Optional[int] = intermediate_size _snake_case : Union[str, Any] = hidden_act _snake_case : Tuple = hidden_dropout_prob _snake_case : Union[str, Any] = attention_probs_dropout_prob _snake_case : Optional[Any] = max_position_embeddings _snake_case : Union[str, Any] = type_vocab_size _snake_case : Any = type_sequence_label_size _snake_case : str = initializer_range _snake_case : Tuple = num_labels _snake_case : Any = num_choices _snake_case : Optional[int] = scope def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Dict = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) _snake_case : Any = None if self.use_input_mask: _snake_case : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case : List[Any] = None _snake_case : Any = None _snake_case : Optional[int] = None if self.use_labels: _snake_case : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) _snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) _snake_case : Tuple = ids_tensor([self.batch_size], self.num_choices ) _snake_case : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, pad_token_id=1, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, ) def UpperCamelCase_ ( self: int, a_: Union[str, Any], a_: Dict, a_: List[str], a_: Any, a_: Any, a_: Any ): '''simple docstring''' _snake_case : Dict = EsmModel(config=a_ ) model.to(a_ ) model.eval() _snake_case : List[str] = model(a_, attention_mask=a_ ) _snake_case : Any = model(a_ ) _snake_case : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size) ) def UpperCamelCase_ ( self: Tuple, a_: int, a_: Dict, a_: Optional[Any], a_: str, a_: Union[str, Any], a_: List[str] ): '''simple docstring''' _snake_case : Union[str, Any] = EsmForMaskedLM(config=a_ ) model.to(a_ ) model.eval() _snake_case : Optional[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self: List[Any], a_: Optional[Any], a_: Any, a_: Any, a_: str, a_: Union[str, Any], a_: Tuple ): '''simple docstring''' _snake_case : Optional[int] = self.num_labels _snake_case : Tuple = EsmForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _snake_case : List[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case : Union[str, Any] = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : str = config_and_inputs _snake_case : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase( __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = False lowercase__ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) lowercase__ = () lowercase__ = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) lowercase__ = True def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : str = EsmModelTester(self ) _snake_case : Union[str, Any] = ConfigTester(self, config_class=a_, hidden_size=37 ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case : str = type self.model_tester.create_and_check_model(*a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Tuple = EsmModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Any = self.model_tester.prepare_config_and_inputs()[0] _snake_case : Union[str, Any] = EsmEmbeddings(config=a_ ) _snake_case : Union[str, Any] = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) _snake_case : int = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _snake_case : List[Any] = create_position_ids_from_input_ids(a_, model.padding_idx ) self.assertEqual(position_ids.shape, expected_positions.shape ) self.assertTrue(torch.all(torch.eq(a_, a_ ) ) ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Any = self.model_tester.prepare_config_and_inputs()[0] _snake_case : Optional[int] = EsmEmbeddings(config=a_ ) _snake_case : int = torch.empty(2, 4, 30 ) _snake_case : Any = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _snake_case : int = torch.as_tensor([expected_single_positions, expected_single_positions] ) _snake_case : List[Any] = embeddings.create_position_ids_from_inputs_embeds(a_ ) self.assertEqual(position_ids.shape, expected_positions.shape ) self.assertTrue(torch.all(torch.eq(a_, a_ ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase_ ( self: int ): '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' pass @require_torch class lowercase( __a ): '''simple docstring''' @slow def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' with torch.no_grad(): _snake_case : Optional[Any] = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _snake_case : Union[str, Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) _snake_case : Optional[int] = model(a_ )[0] _snake_case : Tuple = 33 _snake_case : str = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape, a_ ) _snake_case : str = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], a_, atol=1E-4 ) ) @slow def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' with torch.no_grad(): _snake_case : Tuple = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _snake_case : Any = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _snake_case : Optional[int] = model(a_ )[0] # compare the actual values for a slice. _snake_case : Union[str, Any] = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], a_, atol=1E-4 ) )
64
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Optional[int] = int(_lowerCAmelCase ) if decimal in (0, 1): # Exit cases for the recursion return str(_lowerCAmelCase ) UpperCamelCase , UpperCamelCase : Dict = divmod(_lowerCAmelCase , 2 ) return binary_recursive(_lowerCAmelCase ) + str(_lowerCAmelCase ) def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = str(_lowerCAmelCase ).strip() if not number: raise ValueError("No input value was provided" ) UpperCamelCase : Optional[int] = "-" if number.startswith("-" ) else "" UpperCamelCase : Any = number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return F"""{negative}0b{binary_recursive(int(_lowerCAmelCase ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
52
0
import math def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' return math.sqrt(__A ) * math.sqrt(__A ) == num def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' UpperCAmelCase__ = 0 UpperCAmelCase__ = n while left <= right: UpperCAmelCase__ = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: UpperCAmelCase__ = mid - 1 else: UpperCAmelCase__ = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
65
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=24 , A_=2 , A_=6 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=None , A_=1000 , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : Dict = seq_length UpperCamelCase : Tuple = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : Optional[Any] = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : Optional[int] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : Optional[int] = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Optional[int] = scope UpperCamelCase : int = range_bbox def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase : Union[str, Any] = bbox[i, j, 3] UpperCamelCase : int = bbox[i, j, 1] UpperCamelCase : int = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : List[str] = bbox[i, j, 2] UpperCamelCase : Optional[int] = bbox[i, j, 0] UpperCamelCase : Optional[Any] = t UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : str = None if self.use_token_type_ids: UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Dict = None UpperCamelCase : int = None if self.use_labels: UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCamelCase( self ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = LiltModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = model(A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ ) UpperCamelCase : Optional[int] = model(A_ , bbox=A_ , token_type_ids=A_ ) UpperCamelCase : Any = model(A_ , bbox=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = self.num_labels UpperCamelCase : Dict = LiltForTokenClassification(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Dict = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Dict = LiltForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Tuple = config_and_inputs UpperCamelCase : Tuple = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) _UpperCAmelCase :Dict = False _UpperCAmelCase :Union[str, Any] = False def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' return True def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = LiltModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = LiltModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @slow class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base" ).to(A_ ) UpperCamelCase : Tuple = torch.tensor([[1, 2]] , device=A_ ) UpperCamelCase : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=A_ ) # forward pass with torch.no_grad(): UpperCamelCase : Optional[int] = model(input_ids=A_ , bbox=A_ ) UpperCamelCase : List[str] = torch.Size([1, 2, 768] ) UpperCamelCase : Any = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=A_ , ) self.assertTrue(outputs.last_hidden_state.shape , A_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , A_ , atol=1e-3 ) )
52
0
"""simple docstring""" def A_ ( _lowercase, _lowercase ): '''simple docstring''' return 1 if input_a == input_a else 0 def A_ ( ): '''simple docstring''' assert xnor_gate(0, 0 ) == 1 assert xnor_gate(0, 1 ) == 0 assert xnor_gate(1, 0 ) == 0 assert xnor_gate(1, 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
66
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __lowerCamelCase : Union[str, Any] = pytest.mark.integration @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_ ) for x in np.arange(30 ).tolist()]} ) return dset def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() UpperCamelCase : List[Any] = dset.map( lambda A_ , A_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=A_ , keep_in_memory=A_ ) UpperCamelCase : List[str] = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase , UpperCamelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCamelCase , UpperCamelCase : int = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A_ , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch UpperCamelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} UpperCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=A_ ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Optional[int] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCamelCase : Any = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[Any] = 1 UpperCamelCase , UpperCamelCase : Optional[Any] = index.search(A_ ) self.assertRaises(A_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCamelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCamelCase , UpperCamelCase : Tuple = index.search_batch(A_ ) self.assertRaises(A_ , index.search_batch , queries[0] ) UpperCamelCase : Optional[int] = [scores[0] for scores in total_scores] UpperCamelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCamelCase : List[str] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(A_ ): UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dict = faiss.IndexFlat(5 ) UpperCamelCase : Union[str, Any] = FaissIndex(custom_index=A_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: index.save(tmp_file.name ) UpperCamelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : int = 1 UpperCamelCase , UpperCamelCase : Dict = index.search(A_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def A_ ( _lowerCAmelCase ) -> Optional[int]: import faiss UpperCamelCase : Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCamelCase : List[Any] = "index.faiss" UpperCamelCase : List[str] = F"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[int] = 1 UpperCamelCase , UpperCamelCase : List[str] = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = Elasticsearch() UpperCamelCase : Union[str, Any] = {"acknowledged": True} UpperCamelCase : Union[str, Any] = ElasticSearchIndex(es_client=A_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query UpperCamelCase : str = "foo" UpperCamelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : Tuple = index.search(A_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCamelCase : Dict = "foo" UpperCamelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : str = index.search(A_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCamelCase : Dict = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Optional[int] = index.search_batch(A_ ) UpperCamelCase : str = [scores[0] for scores in total_scores] UpperCamelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ ) # batched queries with timeout UpperCamelCase : int = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Union[str, Any] = index.search_batch(A_ , request_timeout=30 ) UpperCamelCase : Union[str, Any] = [scores[0] for scores in total_scores] UpperCamelCase : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ )
52
0
'''simple docstring''' import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __UpperCAmelCase =2 class a__ : def __init__( self : int , *, # begin keyword-only arguments a : Dict="<s>" , a : Dict="<pad>" , a : int="</s>" , a : List[Any]="<unk>" , a : int=None , ): """simple docstring""" __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = bos, unk, pad, eos __lowerCamelCase = [] __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = self.add_symbol(a ) __lowerCamelCase = self.add_symbol(a ) __lowerCamelCase = self.add_symbol(a ) __lowerCamelCase = self.add_symbol(a ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(a ) __lowerCamelCase = len(self.symbols ) def __eq__( self : Dict , a : Tuple ): """simple docstring""" return self.indices == other.indices def __getitem__( self : List[Any] , a : Tuple ): """simple docstring""" if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[str] ): """simple docstring""" return len(self.symbols ) def __contains__( self : Optional[int] , a : List[str] ): """simple docstring""" return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE__ ( cls : str , a : Dict ): """simple docstring""" __lowerCamelCase = cls() d.add_from_file(a ) return d def SCREAMING_SNAKE_CASE__ ( self : Any , a : Tuple , a : Any=1 , a : List[str]=False ): """simple docstring""" if word in self.indices and not overwrite: __lowerCamelCase = self.indices[word] __lowerCamelCase = self.count[idx] + n return idx else: __lowerCamelCase = len(self.symbols ) __lowerCamelCase = idx self.symbols.append(a ) self.count.append(a ) return idx def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : Any ): """simple docstring""" return 0 def SCREAMING_SNAKE_CASE__ ( self : Any , a : str ): """simple docstring""" if isinstance(a , a ): try: with open(a , '''r''' , encoding='''utf-8''' ) as fd: self.add_from_file(a ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('''Incorrect encoding detected in {}, please rebuild the dataset'''.format(a ) ) return __lowerCamelCase = f.readlines() __lowerCamelCase = self._load_meta(a ) for line in lines[indices_start_line:]: try: __lowerCamelCase , __lowerCamelCase = line.rstrip().rsplit(''' ''' , 1 ) if field == "#fairseq:overwrite": __lowerCamelCase = True __lowerCamelCase , __lowerCamelCase = line.rsplit(''' ''' , 1 ) else: __lowerCamelCase = False __lowerCamelCase = int(a ) __lowerCamelCase = line if word in self and not overwrite: raise RuntimeError( '''Duplicate word found when loading Dictionary: \'{}\'. ''' '''Duplicate words can overwrite earlier ones by adding the ''' '''#fairseq:overwrite flag at the end of the corresponding row ''' '''in the dictionary file. If using the Camembert model, please ''' '''download an updated copy of the model file.'''.format(a ) ) self.add_symbol(a , n=a , overwrite=a ) except ValueError: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt> [flags]\'''' ) def __lowerCAmelCase ( UpperCamelCase__ ) -> Tuple: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} __lowerCamelCase = dict((re.sub(r'''@@$''' , '''''' , UpperCamelCase__ ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''' , '''</w>''' , UpperCamelCase__ ), v) for k, v in d.items() ) __lowerCamelCase = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[f"""{k}</w>"""] __lowerCamelCase = d[k] # restore return da def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: # prep if not os.path.exists(UpperCamelCase__ ): raise ValueError(f"""path {biogpt_checkpoint_path} does not exist!""" ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) print(f"""Writing results to {pytorch_dump_folder_path}""" ) # handle various types of models __lowerCamelCase = os.path.join(UpperCamelCase__ , '''checkpoint.pt''' ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f"""path to the file {checkpoint_file} does not exist!""" ) __lowerCamelCase = torch.load(UpperCamelCase__ , map_location='''cpu''' ) __lowerCamelCase = chkpt['''cfg''']['''model'''] # dicts __lowerCamelCase = os.path.join(UpperCamelCase__ , '''dict.txt''' ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f"""path to the file {dict_file} does not exist!""" ) __lowerCamelCase = Dictionary.load(UpperCamelCase__ ) __lowerCamelCase = rewrite_dict_keys(src_dict.indices ) __lowerCamelCase = len(UpperCamelCase__ ) __lowerCamelCase = os.path.join(UpperCamelCase__ , VOCAB_FILES_NAMES['''vocab_file'''] ) print(f"""Generating {src_vocab_file} of {src_vocab_size} records""" ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # merges_file (bpecodes) __lowerCamelCase = os.path.join(UpperCamelCase__ , '''bpecodes''' ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f"""path to the file {bpecodes_file} does not exist!""" ) __lowerCamelCase = os.path.join(UpperCamelCase__ , VOCAB_FILES_NAMES['''merges_file'''] ) shutil.copyfile(UpperCamelCase__ , UpperCamelCase__ ) # model config __lowerCamelCase = os.path.join(UpperCamelCase__ , '''config.json''' ) __lowerCamelCase = { '''activation_dropout''': args['''activation_dropout'''], '''architectures''': ['''BioGptForCausalLM'''], '''attention_probs_dropout_prob''': args['''attention_dropout'''], '''bos_token_id''': 0, '''eos_token_id''': 2, '''hidden_act''': args['''activation_fn'''], '''hidden_dropout_prob''': args['''dropout'''], '''hidden_size''': args['''decoder_embed_dim'''], '''initializer_range''': 0.0_2, '''intermediate_size''': args['''decoder_ffn_embed_dim'''], '''layer_norm_eps''': 1E-12, '''layerdrop''': args['''decoder_layerdrop'''], '''max_position_embeddings''': args['''max_target_positions'''], '''model_type''': '''biogpt''', '''num_attention_heads''': args['''decoder_attention_heads'''], '''num_hidden_layers''': args['''decoder_layers'''], '''pad_token_id''': 1, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_decoder_input_output_embed'''], '''vocab_size''': src_vocab_size, } # good hparam defaults to start with print(f"""Generating {biogpt_model_config_file}""" ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # tokenizer config __lowerCamelCase = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = { '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''model_max_length''': 10_24, '''pad_token''': '''<pad>''', '''special_tokens_map_file''': None, '''tokenizer_class''': '''BioGptTokenizer''', '''unk_token''': '''<unk>''', } print(f"""Generating {biogpt_tokenizer_config_file}""" ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # model __lowerCamelCase = chkpt['''model'''] # remove unneeded keys __lowerCamelCase = [ '''decoder.version''', ] for k in ignore_keys: model_state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('''output_projection.weight''' ): __lowerCamelCase = model_state_dict.pop(UpperCamelCase__ ) else: __lowerCamelCase = model_state_dict.pop(UpperCamelCase__ ) __lowerCamelCase = BioGptConfig.from_pretrained(UpperCamelCase__ ) __lowerCamelCase = BioGptForCausalLM(UpperCamelCase__ ) # check that it loads ok model_new.load_state_dict(UpperCamelCase__ ) # save __lowerCamelCase = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f"""Generating {pytorch_weights_dump_path}""" ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) print('''Conversion is done!''' ) if __name__ == "__main__": __UpperCAmelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--biogpt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) __UpperCAmelCase =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
67
def A_ ( _lowerCAmelCase = 50 ) -> int: UpperCamelCase : List[Any] = [[0] * 3 for _ in range(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 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
52
0
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'autoformer' __lowerCamelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , lowercase = None , lowercase = None , lowercase = "student_t" , lowercase = "nll" , lowercase = 1 , lowercase = [1, 2, 3, 4, 5, 6, 7] , lowercase = True , lowercase = 0 , lowercase = 0 , lowercase = 0 , lowercase = 0 , lowercase = None , lowercase = None , lowercase = 64 , lowercase = 2 , lowercase = 2 , lowercase = 2 , lowercase = 2 , lowercase = 32 , lowercase = 32 , lowercase = "gelu" , lowercase = 0.1 , lowercase = 0.1 , lowercase = 0.1 , lowercase = 0.1 , lowercase = 0.1 , lowercase = 100 , lowercase = 0.02 , lowercase = True , lowercase=True , lowercase = 10 , lowercase = 25 , lowercase = 3 , **lowercase , ) -> Optional[Any]: '''simple docstring''' A__ = prediction_length A__ = context_length if context_length is not None else prediction_length A__ = distribution_output A__ = loss A__ = input_size A__ = num_time_features A__ = lags_sequence A__ = scaling A__ = num_dynamic_real_features A__ = num_static_real_features A__ = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(lowercase ) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`" ) A__ = cardinality else: A__ = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(lowercase ) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`" ) A__ = embedding_dimension else: A__ = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] A__ = num_parallel_samples # Transformer architecture configuration A__ = input_size * len(self.lags_sequence ) + self._number_of_features A__ = d_model A__ = encoder_attention_heads A__ = decoder_attention_heads A__ = encoder_ffn_dim A__ = decoder_ffn_dim A__ = encoder_layers A__ = decoder_layers A__ = dropout A__ = attention_dropout A__ = activation_dropout A__ = encoder_layerdrop A__ = decoder_layerdrop A__ = activation_function A__ = init_std A__ = use_cache # Autoformer A__ = label_length A__ = moving_average A__ = autocorrelation_factor super().__init__(is_encoder_decoder=lowercase , **lowercase ) @property def UpperCamelCase ( self ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
68
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def A_ ( _lowerCAmelCase ) -> dict[str, str]: UpperCamelCase : Optional[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key UpperCamelCase : Tuple = remove_duplicates(key.upper() ) UpperCamelCase : int = len(_lowerCAmelCase ) # First fill cipher with key characters UpperCamelCase : int = {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_lowerCAmelCase ) , 26 ): UpperCamelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase : List[str] = alphabet[i - offset] UpperCamelCase : List[Any] = char return cipher_alphabet def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: return "".join(cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( ) -> None: UpperCamelCase : int = input("Enter message to encode or decode: " ).strip() UpperCamelCase : str = input("Enter keyword: " ).strip() UpperCamelCase : Union[str, Any] = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: UpperCamelCase : List[str] = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) UpperCamelCase : str = create_cipher_map(_lowerCAmelCase ) print(func(_lowerCAmelCase , _lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
52
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''facebook/data2vec-vision-base-ft''': ( '''https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json''' ), } class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = "data2vec-vision" def __init__( self, lowerCAmelCase__=768, lowerCAmelCase__=12, lowerCAmelCase__=12, lowerCAmelCase__=3072, lowerCAmelCase__="gelu", lowerCAmelCase__=0.0, lowerCAmelCase__=0.0, lowerCAmelCase__=0.02, lowerCAmelCase__=1e-12, lowerCAmelCase__=224, lowerCAmelCase__=16, lowerCAmelCase__=3, lowerCAmelCase__=False, lowerCAmelCase__=False, lowerCAmelCase__=False, lowerCAmelCase__=False, lowerCAmelCase__=0.1, lowerCAmelCase__=0.1, lowerCAmelCase__=True, lowerCAmelCase__=[3, 5, 7, 11], lowerCAmelCase__=[1, 2, 3, 6], lowerCAmelCase__=True, lowerCAmelCase__=0.4, lowerCAmelCase__=256, lowerCAmelCase__=1, lowerCAmelCase__=False, lowerCAmelCase__=255, **lowerCAmelCase__, ) -> Optional[int]: super().__init__(**lowerCAmelCase__) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = use_mask_token snake_case_ = use_absolute_position_embeddings snake_case_ = use_relative_position_bias snake_case_ = use_shared_relative_position_bias snake_case_ = layer_scale_init_value snake_case_ = drop_path_rate snake_case_ = use_mean_pooling # decode head attributes (semantic segmentation) snake_case_ = out_indices snake_case_ = pool_scales # auxiliary head attributes (semantic segmentation) snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = semantic_loss_ignore_index class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = version.parse("1.11" ) @property def a_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ]) @property def a_ ( self) -> float: return 1e-4
69
from sklearn.metrics import fa_score import datasets __lowerCamelCase : List[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCamelCase : List[Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCamelCase : str = """ @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 ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def __UpperCamelCase( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ): '''simple docstring''' UpperCamelCase : List[str] = fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
52
0
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class UpperCAmelCase ( nn.Module ): def __init__( self : int , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ) -> Any: super().__init__() _lowerCAmelCase = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference _lowerCAmelCase = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` _lowerCAmelCase = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` _lowerCAmelCase = [1, 0] def lowercase__ ( self : Union[str, Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : List[str]=None , __snake_case : Dict=None , __snake_case : Dict=None , __snake_case : bool = True , ) -> Tuple: _lowerCAmelCase = hidden_states _lowerCAmelCase = [] _lowerCAmelCase = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens _lowerCAmelCase = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] _lowerCAmelCase = self.transformer_index_for_condition[i] _lowerCAmelCase = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] _lowerCAmelCase = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) _lowerCAmelCase = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
70
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = KandinskyInpaintPipeline _UpperCAmelCase :List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] _UpperCAmelCase :Dict = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] _UpperCAmelCase :Optional[int] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _UpperCAmelCase :int = False @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCamelCase( self ): '''simple docstring''' return 100 @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : Optional[int] = MultilingualCLIP(A_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase : List[Any] = UNetaDConditionModel(**A_ ) return model @property def __UpperCamelCase( self ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.dummy_text_encoder UpperCamelCase : str = self.dummy_tokenizer UpperCamelCase : List[Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="epsilon" , thresholding=A_ , ) UpperCamelCase : Optional[Any] = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __UpperCamelCase( self , A_ , A_=0 ): '''simple docstring''' UpperCamelCase : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image UpperCamelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(A_ ) ).convert("RGB" ).resize((256, 256) ) # create mask UpperCamelCase : str = np.ones((64, 64) , dtype=np.floataa ) UpperCamelCase : str = 0 if str(A_ ).startswith("mps" ): UpperCamelCase : int = torch.manual_seed(A_ ) else: UpperCamelCase : Tuple = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase : Union[str, Any] = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = "cpu" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**A_ ) UpperCamelCase : Tuple = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase : List[Any] = output.images UpperCamelCase : List[Any] = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase : List[Any] = image[0, -3:, -3:, -1] UpperCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) UpperCamelCase : Union[str, Any] = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __UpperCamelCase( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) UpperCamelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) UpperCamelCase : Dict = np.ones((768, 768) , dtype=np.floataa ) UpperCamelCase : str = 0 UpperCamelCase : List[Any] = "a hat" UpperCamelCase : Tuple = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) UpperCamelCase : Optional[Any] = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[Any] = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() UpperCamelCase : Dict = pipeline( A_ , image=A_ , mask_image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
52
0
def A ( a_ ,a_ ) -> str: if not (isinstance(a_ ,a_ ) and isinstance(a_ ,a_ )): raise ValueError('longest_common_substring() takes two strings for inputs' ) __UpperCamelCase : str =len(a_ ) __UpperCamelCase : Dict =len(a_ ) __UpperCamelCase : Union[str, Any] =[[0] * (texta_length + 1) for _ in range(texta_length + 1 )] __UpperCamelCase : Dict =0 __UpperCamelCase : Dict =0 for i in range(1 ,texta_length + 1 ): for j in range(1 ,texta_length + 1 ): if texta[i - 1] == texta[j - 1]: __UpperCamelCase : Any =1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: __UpperCamelCase : Dict =i __UpperCamelCase : Optional[Any] =dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
71
class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = set_counts UpperCamelCase : int = max(A_ ) UpperCamelCase : Optional[Any] = len(A_ ) UpperCamelCase : Union[str, Any] = [1] * num_sets UpperCamelCase : Union[str, Any] = list(range(A_ ) ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = self.get_parent(A_ ) UpperCamelCase : Optional[int] = self.get_parent(A_ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] UpperCamelCase : int = 0 UpperCamelCase : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 UpperCamelCase : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] UpperCamelCase : Any = 0 UpperCamelCase : Optional[int] = src_parent UpperCamelCase : int = self.set_counts[src_parent] UpperCamelCase : Any = max(self.max_set , A_ ) return True def __UpperCamelCase( self , A_ ): '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set UpperCamelCase : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
52
0
"""simple docstring""" import argparse from collections import defaultdict import yaml lowerCAmelCase__ = '''docs/source/en/_toctree.yml''' def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : List[Any] = defaultdict(A_ ) _lowerCamelCase : List[Any] = [] _lowerCamelCase : Tuple = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(A_ ) _lowerCamelCase : Optional[Any] = new_doc_list _lowerCamelCase : Tuple = [key for key, value in counts.items() if value > 1] _lowerCamelCase : List[str] = [] for duplicate_key in duplicates: _lowerCamelCase : Optional[int] = list({doc['''title'''] for doc in doc_list if doc['''local'''] == duplicate_key} ) if len(A_ ) > 1: raise ValueError( F'''{duplicate_key} is present several times in the documentation table of content at ''' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) _lowerCamelCase : Optional[int] = sorted(A_, key=lambda A_ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(A_ ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(A_ ) # Sort return overview_doc def snake_case_ ( A_ : str=False ): '''simple docstring''' with open(A_, encoding='''utf-8''' ) as f: _lowerCamelCase : Union[str, Any] = yaml.safe_load(f.read() ) # Get to the API doc _lowerCamelCase : Union[str, Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _lowerCamelCase : List[Any] = content[api_idx]['''sections'''] # Then to the model doc _lowerCamelCase : str = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 _lowerCamelCase : List[str] = api_doc[scheduler_idx]['''sections'''] _lowerCamelCase : Dict = clean_doc_toc(A_ ) _lowerCamelCase : Tuple = False if new_scheduler_doc != scheduler_doc: _lowerCamelCase : List[str] = True if overwrite: _lowerCamelCase : str = new_scheduler_doc if diff: if overwrite: _lowerCamelCase : List[Any] = api_doc with open(A_, '''w''', encoding='''utf-8''' ) as f: f.write(yaml.dump(A_, allow_unicode=A_ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) def snake_case_ ( A_ : Any=False ): '''simple docstring''' with open(A_, encoding='''utf-8''' ) as f: _lowerCamelCase : Dict = yaml.safe_load(f.read() ) # Get to the API doc _lowerCamelCase : Optional[int] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _lowerCamelCase : Union[str, Any] = content[api_idx]['''sections'''] # Then to the model doc _lowerCamelCase : Union[str, Any] = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 _lowerCamelCase : str = False _lowerCamelCase : Tuple = api_doc[pipeline_idx]['''sections'''] _lowerCamelCase : Any = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: _lowerCamelCase : List[str] = pipeline_doc['''section'''] _lowerCamelCase : Optional[Any] = clean_doc_toc(A_ ) if overwrite: _lowerCamelCase : List[str] = new_sub_pipeline_doc new_pipeline_docs.append(A_ ) # sort overall pipeline doc _lowerCamelCase : Any = clean_doc_toc(A_ ) if new_pipeline_docs != pipeline_docs: _lowerCamelCase : Dict = True if overwrite: _lowerCamelCase : Optional[int] = new_pipeline_docs if diff: if overwrite: _lowerCamelCase : Union[str, Any] = api_doc with open(A_, '''w''', encoding='''utf-8''' ) as f: f.write(yaml.dump(A_, allow_unicode=A_ ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCAmelCase__ = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
72
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Any = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a ="""src/diffusers""" a =""".""" # This is to make sure the diffusers module imported is the one in the repo. a =importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) a =spec.loader.load_module() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: return line.startswith(lowerCamelCase__ ) or len(lowerCamelCase__ ) <= 1 or re.search(R'^\s*\)(\s*->.*:|:)\s*$' , lowerCamelCase__ ) is not None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[Any] = object_name.split('.' ) __lowerCamelCase : List[Any] = 0 # First let's find the module where our object lives. __lowerCamelCase : Union[str, Any] = parts[i] while i < len(lowerCamelCase__ ) and not os.path.isfile(os.path.join(lowerCamelCase__ , F"{module}.py" ) ): i += 1 if i < len(lowerCamelCase__ ): __lowerCamelCase : Dict = os.path.join(lowerCamelCase__ , parts[i] ) if i >= len(lowerCamelCase__ ): raise ValueError(F"`object_name` should begin with the name of a module of diffusers but got {object_name}." ) with open(os.path.join(lowerCamelCase__ , F"{module}.py" ) , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowerCamelCase : List[Any] = f.readlines() # Now let's find the class / func in the code! __lowerCamelCase : str = '' __lowerCamelCase : Optional[int] = 0 for name in parts[i + 1 :]: while ( line_index < len(lowerCamelCase__ ) and re.search(RF"^{indent}(class|def)\s+{name}(\(|\:)" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lowerCamelCase__ ): raise ValueError(F" {object_name} does not match any function or class in {module}." ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __lowerCamelCase : Union[str, Any] = line_index while line_index < len(lowerCamelCase__ ) and _should_continue(lines[line_index] , lowerCamelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __lowerCamelCase : List[str] = lines[start_index:line_index] return "".join(lowerCamelCase__ ) a =re.compile(r"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") a =re.compile(r"""^\s*(\S+)->(\S+)(\s+.*|$)""") a =re.compile(r"""<FILL\s+[^>]*>""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Dict = code.split('\n' ) __lowerCamelCase : Tuple = 0 while idx < len(lowerCamelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(lowerCamelCase__ ): return re.search(R'^(\s*)\S' , lines[idx] ).groups()[0] return "" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: __lowerCamelCase : Any = len(get_indent(lowerCamelCase__ ) ) > 0 if has_indent: __lowerCamelCase : Optional[Any] = F"class Bla:\n{code}" __lowerCamelCase : List[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 , preview=lowerCamelCase__ ) __lowerCamelCase : Any = black.format_str(lowerCamelCase__ , mode=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = style_docstrings_in_code(lowerCamelCase__ ) return result[len('class Bla:\n' ) :] if has_indent else result def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=False ) -> int: with open(lowerCamelCase__ , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowerCamelCase : Dict = f.readlines() __lowerCamelCase : Any = [] __lowerCamelCase : Optional[int] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lowerCamelCase__ ): __lowerCamelCase : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = search.groups() __lowerCamelCase : Any = find_code_in_diffusers(lowerCamelCase__ ) __lowerCamelCase : List[Any] = get_indent(lowerCamelCase__ ) __lowerCamelCase : List[Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 __lowerCamelCase : Optional[Any] = theoretical_indent __lowerCamelCase : Tuple = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __lowerCamelCase : int = True while line_index < len(lowerCamelCase__ ) and should_continue: line_index += 1 if line_index >= len(lowerCamelCase__ ): break __lowerCamelCase : Any = lines[line_index] __lowerCamelCase : List[str] = _should_continue(lowerCamelCase__ , lowerCamelCase__ ) and re.search(F"^{indent}# End copy" , lowerCamelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __lowerCamelCase : int = lines[start_index:line_index] __lowerCamelCase : List[Any] = ''.join(lowerCamelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies __lowerCamelCase : int = [line for line in theoretical_code.split('\n' ) if _re_copy_warning.search(lowerCamelCase__ ) is None] __lowerCamelCase : Union[str, Any] = '\n'.join(lowerCamelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(lowerCamelCase__ ) > 0: __lowerCamelCase : int = replace_pattern.replace('with' , '' ).split(',' ) __lowerCamelCase : Optional[Any] = [_re_replace_pattern.search(lowerCamelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Tuple = pattern.groups() __lowerCamelCase : List[Any] = re.sub(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if option.strip() == "all-casing": __lowerCamelCase : Union[str, Any] = re.sub(obja.lower() , obja.lower() , lowerCamelCase__ ) __lowerCamelCase : Dict = re.sub(obja.upper() , obja.upper() , lowerCamelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __lowerCamelCase : Dict = blackify(lines[start_index - 1] + theoretical_code ) __lowerCamelCase : Any = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __lowerCamelCase : List[str] = lines[:start_index] + [theoretical_code] + lines[line_index:] __lowerCamelCase : Optional[int] = start_index + 1 if overwrite and len(lowerCamelCase__ ) > 0: # Warn the user a file has been modified. print(F"Detected changes, rewriting {filename}." ) with open(lowerCamelCase__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(lowerCamelCase__ ) return diffs def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = False ) -> Any: __lowerCamelCase : List[str] = glob.glob(os.path.join(lowerCamelCase__ , '**/*.py' ) , recursive=lowerCamelCase__ ) __lowerCamelCase : Any = [] for filename in all_files: __lowerCamelCase : str = is_copy_consistent(lowerCamelCase__ , lowerCamelCase__ ) diffs += [F"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] if not overwrite and len(lowerCamelCase__ ) > 0: __lowerCamelCase : Union[str, Any] = '\n'.join(lowerCamelCase__ ) raise Exception( 'Found the following copy inconsistencies:\n' + diff + '\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.' ) if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") a =parser.parse_args() check_copies(args.fix_and_overwrite)
73
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class A__ ( __snake_case , __snake_case ): _UpperCAmelCase :Optional[int] = 'convnextv2' def __init__( self , A_=3 , A_=4 , A_=4 , A_=None , A_=None , A_="gelu" , A_=0.02 , A_=1e-12 , A_=0.0 , A_=224 , A_=None , A_=None , **A_ , ): '''simple docstring''' super().__init__(**A_ ) UpperCamelCase : Dict = num_channels UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Union[str, Any] = num_stages UpperCamelCase : List[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCamelCase : List[str] = [3, 3, 9, 3] if depths is None else depths UpperCamelCase : Dict = hidden_act UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : str = drop_path_rate UpperCamelCase : List[str] = image_size UpperCamelCase : List[str] = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase : str = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
52
0
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') _lowercase = parser.parse_args() _lowercase = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
74
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_lowerCAmelCase ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def A_ ( ) -> Tuple: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def A_ ( ) -> Optional[int]: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_lowerCAmelCase ): http_head("https://huggingface.co" )
52
0
'''simple docstring''' def a_ ( __snake_case : int = 400_0000 ) -> int: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_, lowerCamelCase_ =0, 1 while b <= n: if b % 2 == 0: even_fibs.append(__snake_case ) lowerCamelCase_, lowerCamelCase_ =b, a + b return sum(__snake_case ) if __name__ == "__main__": print(F"""{solution() = }""")
75
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCamelCase : List[Any] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ __lowerCamelCase : Optional[int] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ __lowerCamelCase : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def A_ ( _lowerCAmelCase ) -> str: def remove_articles(_lowerCAmelCase ): UpperCamelCase : Tuple = re.compile(r"\b(a|an|the)\b" , re.UNICODE ) return re.sub(_lowerCAmelCase , " " , _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase ): UpperCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = [any(compute_exact(_lowerCAmelCase , _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 100 def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Optional[int] = Counter(_lowerCAmelCase ) UpperCamelCase : List[Any] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : Tuple = scount * numref UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Tuple = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Dict = ccount * numref # KEEP UpperCamelCase : List[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Union[str, Any] = keepgramcounter_rep & rgramcounter UpperCamelCase : Dict = sgramcounter_rep & rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Any = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Union[str, Any] = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : Any = sgramcounter_rep - cgramcounter_rep UpperCamelCase : str = delgramcounter_rep - rgramcounter UpperCamelCase : Any = sgramcounter_rep - rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Dict = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : str = deltmpscorea / len(_lowerCAmelCase ) # ADDITION UpperCamelCase : List[str] = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : List[str] = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) UpperCamelCase : Dict = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 UpperCamelCase : Tuple = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Tuple = addtmpscore / len(_lowerCAmelCase ) UpperCamelCase : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : List[str] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: UpperCamelCase : int = len(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = ssent.split(" " ) UpperCamelCase : Dict = csent.split(" " ) UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Any = [] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : str = [] UpperCamelCase : str = [] UpperCamelCase : Dict = [] UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = [] for rsent in rsents: UpperCamelCase : List[Any] = rsent.split(" " ) UpperCamelCase : List[str] = [] UpperCamelCase : int = [] UpperCamelCase : Tuple = [] ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : List[Any] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : List[str] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : str = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : Union[str, Any] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Union[str, Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = "13a" , _lowerCAmelCase = True ) -> Optional[Any]: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : Dict = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : str = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: UpperCamelCase : Dict = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": UpperCamelCase : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase , escape=_lowerCAmelCase ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase ) else: UpperCamelCase : Union[str, Any] = sentence if not return_str: UpperCamelCase : Tuple = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError("Sources length must match predictions and references lengths." ) UpperCamelCase : Optional[Any] = 0 for src, pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ) , normalize(_lowerCAmelCase ) , [normalize(_lowerCAmelCase ) for sent in refs] ) UpperCamelCase : Optional[int] = sari_score / len(_lowerCAmelCase ) return 100 * sari_score def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase="exp" , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> List[str]: UpperCamelCase : Optional[Any] = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] UpperCamelCase : Tuple = sacrebleu.corpus_bleu( _lowerCAmelCase , _lowerCAmelCase , smooth_method=_lowerCAmelCase , smooth_value=_lowerCAmelCase , force=_lowerCAmelCase , lowercase=_lowerCAmelCase , use_effective_order=_lowerCAmelCase , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = {} result.update({"sari": compute_sari(sources=A_ , predictions=A_ , references=A_ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A_ , references=A_ )} ) result.update({"exact": compute_em(predictions=A_ , references=A_ )} ) return result
52
0
"""simple docstring""" import inspect import unittest class UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self ) -> List[str]: try: import diffusers # noqa: F401 except ImportError: assert False def _UpperCAmelCase ( self ) -> Optional[int]: import diffusers from diffusers.dependency_versions_table import deps lowercase__ : Any = inspect.getmembers(a , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": lowercase__ : Optional[int] = 'k-diffusion' elif backend == "invisible_watermark": lowercase__ : Optional[Any] = 'invisible-watermark' assert backend in deps, f"""{backend} is not in the deps table!"""
77
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : str = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = 'roberta' def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Any = type_vocab_size UpperCamelCase : int = initializer_range UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = position_embedding_type UpperCamelCase : Any = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
52
0
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __UpperCamelCase = (DDPMScheduler,) def UpperCAmelCase__ ( self :int , **lowercase_ :Optional[Any] ) -> Tuple: UpperCAmelCase = { 'num_train_timesteps': 10_00, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**lowercase_ ) return config def UpperCAmelCase__ ( self :int ) -> Union[str, Any]: for timesteps in [1, 5, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=lowercase_ ) def UpperCAmelCase__ ( self :int ) -> Optional[Any]: for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_ ) def UpperCAmelCase__ ( self :int ) -> int: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_ ) def UpperCAmelCase__ ( self :List[Any] ) -> List[Any]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowercase_ ) def UpperCAmelCase__ ( self :Optional[int] ) -> Tuple: for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowercase_ ) def UpperCAmelCase__ ( self :List[str] ) -> Dict: self.check_over_configs(thresholding=lowercase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowercase_ , prediction_type=lowercase_ , sample_max_value=lowercase_ , ) def UpperCAmelCase__ ( self :List[str] ) -> Dict: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Optional[Any]: for t in [0, 5_00, 9_99]: self.check_over_forward(time_step=lowercase_ ) def UpperCAmelCase__ ( self :Any ) -> Tuple: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 ) - 0.02 ) ) < 1E-5 def UpperCAmelCase__ ( self :Union[str, Any] ) -> Dict: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = len(lowercase_ ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter UpperCAmelCase = torch.manual_seed(0 ) for t in reversed(range(lowercase_ ) ): # 1. predict noise residual UpperCAmelCase = model(lowercase_ , lowercase_ ) # 2. predict previous mean of sample x_t-1 UpperCAmelCase = scheduler.step(lowercase_ , lowercase_ , lowercase_ , generator=lowercase_ ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance UpperCAmelCase = pred_prev_sample UpperCAmelCase = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def UpperCAmelCase__ ( self :Optional[int] ) -> Optional[Any]: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(prediction_type='v_prediction' ) UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = len(lowercase_ ) UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter UpperCAmelCase = torch.manual_seed(0 ) for t in reversed(range(lowercase_ ) ): # 1. predict noise residual UpperCAmelCase = model(lowercase_ , lowercase_ ) # 2. predict previous mean of sample x_t-1 UpperCAmelCase = scheduler.step(lowercase_ , lowercase_ , lowercase_ , generator=lowercase_ ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance UpperCAmelCase = pred_prev_sample UpperCAmelCase = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[Any]: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = [1_00, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=lowercase_ ) UpperCAmelCase = scheduler.timesteps for i, timestep in enumerate(lowercase_ ): if i == len(lowercase_ ) - 1: UpperCAmelCase = -1 else: UpperCAmelCase = timesteps[i + 1] UpperCAmelCase = scheduler.previous_timestep(lowercase_ ) UpperCAmelCase = prev_t.item() self.assertEqual(lowercase_ , lowercase_ ) def UpperCAmelCase__ ( self :Any ) -> Union[str, Any]: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = [1_00, 87, 50, 51, 0] with self.assertRaises(lowercase_ , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=lowercase_ ) def UpperCAmelCase__ ( self :Any ) -> Optional[Any]: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = [1_00, 87, 50, 1, 0] UpperCAmelCase = len(lowercase_ ) with self.assertRaises(lowercase_ , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=lowercase_ , timesteps=lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Union[str, Any]: UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**lowercase_ ) UpperCAmelCase = [scheduler.config.num_train_timesteps] with self.assertRaises( lowercase_ , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=lowercase_ )
78
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_case ): def __init__( self , A_ , A_ ): '''simple docstring''' super().__init__() self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = 100 , A_ = None , A_ = None , A_ = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCamelCase : str = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) UpperCamelCase : Union[str, Any] = int(A_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : List[str] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) UpperCamelCase : Any = int(A_ ) UpperCamelCase : Union[str, Any] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : Optional[int] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(A_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) UpperCamelCase : Optional[Any] = randn_tensor(A_ , generator=A_ , device=self.device , dtype=A_ ) # set step values self.scheduler.set_timesteps(A_ , device=audio.device ) UpperCamelCase : Optional[int] = self.scheduler.timesteps.to(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(A_ , A_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : int = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase : Optional[Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A_ )
52
0
'''simple docstring''' import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC lowerCamelCase_ = parse(importlib.metadata.version('''torch''')) def __lowercase ( __lowercase , __lowercase , __lowercase ) -> List[Any]: '''simple docstring''' if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(F'''`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}''' ) _A = STR_OPERATION_TO_FUNC[operation] if isinstance(__lowercase , __lowercase ): _A = parse(importlib.metadata.version(__lowercase ) ) return operation(__lowercase , parse(__lowercase ) ) def __lowercase ( __lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' return compare_versions(__lowercase , __lowercase , __lowercase )
79
import functools def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: UpperCamelCase : Optional[int] = len(_lowerCAmelCase ) UpperCamelCase : List[str] = len(_lowerCAmelCase ) @functools.cache def min_distance(_lowerCAmelCase , _lowerCAmelCase ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa UpperCamelCase : Union[str, Any] = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , _lowerCAmelCase ) , 1 + min_distance(_lowerCAmelCase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
52
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : List[Any] = { 'configuration_convnext': ['CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvNextConfig', 'ConvNextOnnxConfig'] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = ['ConvNextFeatureExtractor'] a__ : List[Any] = ['ConvNextImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ 'CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvNextForImageClassification', 'ConvNextModel', 'ConvNextPreTrainedModel', 'ConvNextBackbone', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TFConvNextForImageClassification', 'TFConvNextModel', 'TFConvNextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure)
80
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin __lowerCamelCase : str = random.Random() if is_torch_available(): import torch def A_ ( _lowerCAmelCase , _lowerCAmelCase=1.0 , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> Optional[Any]: if rng is None: UpperCamelCase : Optional[int] = global_rng UpperCamelCase : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class A__ ( unittest.TestCase ): def __init__( self , A_ , A_=7 , A_=400 , A_=2000 , A_=1 , A_=0.0 , A_=1_6000 , A_=True , A_=True , ): '''simple docstring''' UpperCamelCase : Tuple = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Union[str, Any] = feature_size UpperCamelCase : List[str] = padding_value UpperCamelCase : Optional[Any] = sampling_rate UpperCamelCase : List[str] = return_attention_mask UpperCamelCase : List[Any] = do_normalize def __UpperCamelCase( self ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCamelCase( self , A_=False , A_=False ): '''simple docstring''' def _flatten(A_ ): return list(itertools.chain(*A_ ) ) if equal_length: UpperCamelCase : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Dict = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Union[str, Any] = [np.asarray(A_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = ASTFeatureExtractor def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = ASTFeatureExtractionTester(self ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = [np.asarray(A_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Dict = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCamelCase : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values UpperCamelCase : Any = feat_extract(A_ , padding=A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(A_ ) UpperCamelCase : Any = feat_extract(A_ , return_tensors="np" ).input_values UpperCamelCase : List[str] = feat_extract(A_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(A_ , A_ ): self.assertTrue(np.allclose(A_ , A_ , atol=1e-3 ) ) @require_torch def __UpperCamelCase( self ): '''simple docstring''' import torch UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : str = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __UpperCamelCase( self , A_ ): '''simple docstring''' from datasets import load_dataset UpperCamelCase : Dict = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech UpperCamelCase : Any = ds.sort("id" ).select(range(A_ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : Tuple = ASTFeatureExtractor() UpperCamelCase : str = feature_extractor(A_ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A_ , atol=1e-4 ) )
52
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" @staticmethod @abstractmethod def SCREAMING_SNAKE_CASE ( __A ) -> str: raise NotImplementedError() @abstractmethod def SCREAMING_SNAKE_CASE ( self ) -> str: raise NotImplementedError()
81
import pickle import numpy as np from matplotlib import pyplot as plt class A__ : def __init__( self , A_ , A_ , A_ , A_ , A_ , A_=0.2 , A_=0.2 ): '''simple docstring''' UpperCamelCase : int = bp_numa UpperCamelCase : int = bp_numa UpperCamelCase : List[Any] = bp_numa UpperCamelCase : Optional[int] = conva_get[:2] UpperCamelCase : Optional[Any] = conva_get[2] UpperCamelCase : Dict = size_pa UpperCamelCase : Union[str, Any] = rate_w UpperCamelCase : Dict = rate_t UpperCamelCase : Union[str, Any] = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] UpperCamelCase : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) UpperCamelCase : Optional[Any] = -2 * np.random.rand(self.conva[1] ) + 1 UpperCamelCase : Any = -2 * np.random.rand(self.num_bpa ) + 1 UpperCamelCase : int = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(A_ , "wb" ) as f: pickle.dump(A_ , A_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __UpperCamelCase( cls , A_ ): '''simple docstring''' with open(A_ , "rb" ) as f: UpperCamelCase : Optional[Any] = pickle.load(A_ ) # noqa: S301 UpperCamelCase : List[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) UpperCamelCase : Union[str, Any] = model_dic.get("size_pooling1" ) UpperCamelCase : List[Any] = model_dic.get("num_bp1" ) UpperCamelCase : Dict = model_dic.get("num_bp2" ) UpperCamelCase : Dict = model_dic.get("num_bp3" ) UpperCamelCase : Dict = model_dic.get("rate_weight" ) UpperCamelCase : str = model_dic.get("rate_thre" ) # create model instance UpperCamelCase : Any = CNN(A_ , A_ , A_ , A_ , A_ , A_ , A_ ) # modify model parameter UpperCamelCase : str = model_dic.get("w_conv1" ) UpperCamelCase : Optional[Any] = model_dic.get("wkj" ) UpperCamelCase : int = model_dic.get("vji" ) UpperCamelCase : Any = model_dic.get("thre_conv1" ) UpperCamelCase : Optional[int] = model_dic.get("thre_bp2" ) UpperCamelCase : Union[str, Any] = model_dic.get("thre_bp3" ) return conv_ins def __UpperCamelCase( self , A_ ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def __UpperCamelCase( self , A_ ): '''simple docstring''' return round(A_ , 3 ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = convs[0] UpperCamelCase : Optional[Any] = convs[1] UpperCamelCase : Optional[Any] = np.shape(A_ )[0] # get the data slice of original image data, data_focus UpperCamelCase : List[str] = [] for i_focus in range(0 , size_data - size_conv + 1 , A_ ): for j_focus in range(0 , size_data - size_conv + 1 , A_ ): UpperCamelCase : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(A_ ) # calculate the feature map of every single kernel, and saved as list of matrix UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(A_ ): UpperCamelCase : str = [] for i_focus in range(len(A_ ) ): UpperCamelCase : List[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(A_ ) ) UpperCamelCase : Optional[int] = np.asmatrix(A_ ).reshape( A_ , A_ ) data_featuremap.append(A_ ) # expanding the data slice to One dimenssion UpperCamelCase : List[Any] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(A_ ) ) UpperCamelCase : Tuple = np.asarray(A_ ) return focus_list, data_featuremap def __UpperCamelCase( self , A_ , A_ , A_="average_pool" ): '''simple docstring''' UpperCamelCase : Any = len(featuremaps[0] ) UpperCamelCase : str = int(size_map / size_pooling ) UpperCamelCase : Optional[int] = [] for i_map in range(len(A_ ) ): UpperCamelCase : Tuple = featuremaps[i_map] UpperCamelCase : Any = [] for i_focus in range(0 , A_ , A_ ): for j_focus in range(0 , A_ , A_ ): UpperCamelCase : int = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(A_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(A_ ) ) UpperCamelCase : Optional[Any] = np.asmatrix(A_ ).reshape(A_ , A_ ) featuremap_pooled.append(A_ ) return featuremap_pooled def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = [] for i in range(len(A_ ) ): UpperCamelCase : List[Any] = np.shape(data[i] ) UpperCamelCase : str = data[i].reshape(1 , shapes[0] * shapes[1] ) UpperCamelCase : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(A_ ) UpperCamelCase : Any = np.asarray(A_ ) return data_expanded def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : List[Any] = np.asarray(A_ ) UpperCamelCase : List[Any] = np.shape(A_ ) UpperCamelCase : Any = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[int] = 0 for i_map in range(A_ ): UpperCamelCase : int = np.ones((size_map, size_map) ) for i in range(0 , A_ , A_ ): for j in range(0 , A_ , A_ ): UpperCamelCase : str = pd_pool[ i_pool ] UpperCamelCase : str = i_pool + 1 UpperCamelCase : str = np.multiply( A_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(A_ ) return pd_all def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=bool ): '''simple docstring''' print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(A_ )) ) print((" - - Shape: Teach_Data ", np.shape(A_ )) ) UpperCamelCase : List[str] = 0 UpperCamelCase : Union[str, Any] = [] UpperCamelCase : int = 1_0000 while rp < n_repeat and mse >= error_accuracy: UpperCamelCase : Tuple = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(A_ ) ): # print('------------Learning Image: %d--------------'%p) UpperCamelCase : Any = np.asmatrix(datas_train[p] ) UpperCamelCase : List[str] = np.asarray(datas_teach[p] ) UpperCamelCase , UpperCamelCase : Dict = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : Tuple = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : int = np.shape(A_ ) UpperCamelCase : List[str] = self._expand(A_ ) UpperCamelCase : Optional[int] = data_bp_input UpperCamelCase : str = np.dot(A_ , self.vji.T ) - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) UpperCamelCase : List[Any] = np.dot(A_ , self.wkj.T ) - self.thre_bpa UpperCamelCase : Dict = self.sig(A_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- UpperCamelCase : List[Any] = np.multiply( (data_teach - bp_outa) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : str = np.multiply( np.dot(A_ , self.wkj ) , np.multiply(A_ , (1 - bp_outa) ) ) UpperCamelCase : Any = np.dot(A_ , self.vji ) UpperCamelCase : Dict = pd_i_all / (self.size_poolinga * self.size_poolinga) UpperCamelCase : List[Any] = pd_conva_pooled.T.getA().tolist() UpperCamelCase : List[Any] = self._calculate_gradient_from_pool( A_ , A_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): UpperCamelCase : List[Any] = self._expand_mat(pd_conva_all[k_conv] ) UpperCamelCase : List[Any] = self.rate_weight * np.dot(A_ , A_ ) UpperCamelCase : str = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) UpperCamelCase : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer UpperCamelCase : Optional[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight UpperCamelCase : List[Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight UpperCamelCase : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre UpperCamelCase : List[str] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image UpperCamelCase : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) UpperCamelCase : Any = rp + 1 UpperCamelCase : Union[str, Any] = error_count / patterns all_mse.append(A_ ) def draw_error(): UpperCamelCase : Tuple = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(A_ , "+-" ) plt.plot(A_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(A_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(A_ )) ) for p in range(len(A_ ) ): UpperCamelCase : int = np.asmatrix(datas_test[p] ) UpperCamelCase , UpperCamelCase : Any = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : List[str] = self.pooling(A_ , self.size_poolinga ) UpperCamelCase : Dict = self._expand(A_ ) UpperCamelCase : List[Any] = data_bp_input UpperCamelCase : Any = bp_outa * self.vji.T - self.thre_bpa UpperCamelCase : List[Any] = self.sig(A_ ) UpperCamelCase : int = bp_outa * self.wkj.T - self.thre_bpa UpperCamelCase : Optional[int] = self.sig(A_ ) produce_out.extend(bp_outa.getA().tolist() ) UpperCamelCase : List[str] = [list(map(self.do_round , A_ ) ) for each in produce_out] return np.asarray(A_ ) def __UpperCamelCase( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = np.asmatrix(A_ ) UpperCamelCase , UpperCamelCase : List[Any] = self.convolute( A_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) UpperCamelCase : str = self.pooling(A_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
52
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig A__ = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''albert''' def __init__( self , _snake_case=30000 , _snake_case=128 , _snake_case=4096 , _snake_case=12 , _snake_case=1 , _snake_case=64 , _snake_case=16384 , _snake_case=1 , _snake_case="gelu_new" , _snake_case=0 , _snake_case=0 , _snake_case=512 , _snake_case=2 , _snake_case=0.02 , _snake_case=1e-12 , _snake_case=0.1 , _snake_case="absolute" , _snake_case=0 , _snake_case=2 , _snake_case=3 , **_snake_case , ): """simple docstring""" super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) _lowerCAmelCase = vocab_size _lowerCAmelCase = embedding_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_hidden_groups _lowerCAmelCase = num_attention_heads _lowerCAmelCase = inner_group_num _lowerCAmelCase = hidden_act _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = classifier_dropout_prob _lowerCAmelCase = position_embedding_type class __lowerCAmelCase ( lowerCamelCase__ ): @property def snake_case ( self ): """simple docstring""" if self.task == "multiple-choice": _lowerCAmelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCAmelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
82
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Any = { """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""", # See all BART models at https://huggingface.co/models?filter=bart } class A__ ( __snake_case ): _UpperCAmelCase :Dict = 'bart' _UpperCAmelCase :str = ['past_key_values'] _UpperCAmelCase :Any = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , A_=5_0265 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=3 , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , **A_ , ): '''simple docstring''' UpperCamelCase : int = vocab_size UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Any = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = encoder_attention_heads UpperCamelCase : Optional[int] = decoder_ffn_dim UpperCamelCase : List[str] = decoder_layers UpperCamelCase : Optional[int] = decoder_attention_heads UpperCamelCase : int = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Tuple = activation_dropout UpperCamelCase : Tuple = activation_function UpperCamelCase : int = init_std UpperCamelCase : List[Any] = encoder_layerdrop UpperCamelCase : List[str] = decoder_layerdrop UpperCamelCase : Dict = classifier_dropout UpperCamelCase : Optional[int] = use_cache UpperCamelCase : List[Any] = encoder_layers UpperCamelCase : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , A_ ): UpperCamelCase : 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." ) class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase : List[str] = {0: "batch"} UpperCamelCase : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase : Dict = {0: "batch", 1: "decoder_sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(A_ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase : Any = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase , UpperCamelCase : Optional[int] = self.num_layers for i in range(A_ ): UpperCamelCase : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase : Optional[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def __UpperCamelCase( self ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Tuple = super().outputs else: UpperCamelCase : Dict = super(A_ , self ).outputs if self.use_past: UpperCamelCase , UpperCamelCase : int = self.num_layers for i in range(A_ ): UpperCamelCase : int = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase : Tuple = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) # Generate decoder inputs UpperCamelCase : List[Any] = seq_length if not self.use_past else 1 UpperCamelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) UpperCamelCase : Optional[int] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase : List[Any] = dict(**A_ , **A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Optional[Any] = common_inputs["input_ids"].shape UpperCamelCase : List[Any] = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase , UpperCamelCase : List[str] = self.num_attention_heads UpperCamelCase : int = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : List[Any] = decoder_seq_length + 3 UpperCamelCase : str = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase : int = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(A_ , A_ )] , dim=1 ) UpperCamelCase : int = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase , UpperCamelCase : Union[str, Any] = self.num_layers UpperCamelCase : Any = min(A_ , A_ ) UpperCamelCase : List[str] = max(A_ , A_ ) - min_num_layers UpperCamelCase : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(A_ ): common_inputs["past_key_values"].append( ( torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), torch.zeros(A_ ), ) ) # TODO: test this. UpperCamelCase : Optional[Any] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(A_ , A_ ): common_inputs["past_key_values"].append((torch.zeros(A_ ), torch.zeros(A_ )) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : int = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase , UpperCamelCase : Union[str, Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase : Optional[Any] = seqlen + 2 UpperCamelCase , UpperCamelCase : List[Any] = self.num_layers UpperCamelCase , UpperCamelCase : Optional[int] = self.num_attention_heads UpperCamelCase : str = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase : Optional[Any] = common_inputs["attention_mask"].dtype UpperCamelCase : int = torch.cat( [common_inputs["attention_mask"], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) UpperCamelCase : Optional[Any] = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(A_ ) ] return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase : Union[str, Any] = tokenizer.num_special_tokens_to_add(A_ ) UpperCamelCase : int = compute_effective_axis_dimension( A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase : int = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase : Dict = dict(tokenizer(A_ , return_tensors=A_ ) ) return common_inputs def __UpperCamelCase( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[int] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) elif self.task == "causal-lm": UpperCamelCase : List[str] = self._generate_dummy_inputs_for_causal_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) else: UpperCamelCase : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) return common_inputs def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCamelCase : Optional[Any] = super()._flatten_past_key_values_(A_ , A_ , A_ , A_ ) else: UpperCamelCase : Optional[Any] = super(A_ , self )._flatten_past_key_values_( A_ , A_ , A_ , A_ )
52
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase__ ( lowercase ): lowercase__ = 42 lowercase__ = 42 class lowercase__ ( nn.Module ): lowercase__ = 42 lowercase__ = (16, 32, 96, 2_56) lowercase__ = jnp.floataa def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _UpperCamelCase : List[str] = nn.Conv( self.block_out_channels[0] ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) _UpperCamelCase : List[Any] = [] for i in range(len(self.block_out_channels ) - 1 ): _UpperCamelCase : Optional[int] = self.block_out_channels[i] _UpperCamelCase : List[Any] = self.block_out_channels[i + 1] _UpperCamelCase : int = nn.Conv( lowerCamelCase__ ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) blocks.append(lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = nn.Conv( lowerCamelCase__ ,kernel_size=(3, 3) ,strides=(2, 2) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) blocks.append(lowerCamelCase__ ) _UpperCamelCase : Any = blocks _UpperCamelCase : List[str] = nn.Conv( self.conditioning_embedding_channels ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) def __call__( self : List[Any] ,lowerCamelCase__ : Tuple ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.conv_in(lowerCamelCase__ ) _UpperCamelCase : List[Any] = nn.silu(lowerCamelCase__ ) for block in self.blocks: _UpperCamelCase : List[str] = block(lowerCamelCase__ ) _UpperCamelCase : Dict = nn.silu(lowerCamelCase__ ) _UpperCamelCase : List[str] = self.conv_out(lowerCamelCase__ ) return embedding @flax_register_to_config class lowercase__ ( nn.Module , lowercase , lowercase ): lowercase__ = 32 lowercase__ = 4 lowercase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowercase__ = False lowercase__ = (3_20, 6_40, 12_80, 12_80) lowercase__ = 2 lowercase__ = 8 lowercase__ = None lowercase__ = 12_80 lowercase__ = 0.0 lowercase__ = False lowercase__ = jnp.floataa lowercase__ = True lowercase__ = 0 lowercase__ = "rgb" lowercase__ = (16, 32, 96, 2_56) def UpperCamelCase_ ( self : List[Any] ,lowerCamelCase__ : jax.random.KeyArray ): '''simple docstring''' # init input tensors _UpperCamelCase : Optional[Any] = (1, self.in_channels, self.sample_size, self.sample_size) _UpperCamelCase : Tuple = jnp.zeros(lowerCamelCase__ ,dtype=jnp.floataa ) _UpperCamelCase : Optional[int] = jnp.ones((1,) ,dtype=jnp.intaa ) _UpperCamelCase : Any = jnp.zeros((1, 1, self.cross_attention_dim) ,dtype=jnp.floataa ) _UpperCamelCase : Tuple = (1, 3, self.sample_size * 8, self.sample_size * 8) _UpperCamelCase : Union[str, Any] = jnp.zeros(lowerCamelCase__ ,dtype=jnp.floataa ) _UpperCamelCase , _UpperCamelCase : Optional[int] = jax.random.split(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )["params"] def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = self.block_out_channels _UpperCamelCase : Optional[int] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _UpperCamelCase : Dict = self.num_attention_heads or self.attention_head_dim # input _UpperCamelCase : Optional[int] = nn.Conv( block_out_channels[0] ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) # time _UpperCamelCase : Union[str, Any] = FlaxTimesteps( block_out_channels[0] ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.config.freq_shift ) _UpperCamelCase : List[Any] = FlaxTimestepEmbedding(lowerCamelCase__ ,dtype=self.dtype ) _UpperCamelCase : str = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] ,block_out_channels=self.conditioning_embedding_out_channels ,) _UpperCamelCase : Tuple = self.only_cross_attention if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase : int = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase : List[str] = (num_attention_heads,) * len(self.down_block_types ) # down _UpperCamelCase : List[Any] = [] _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : Dict = block_out_channels[0] _UpperCamelCase : int = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) for i, down_block_type in enumerate(self.down_block_types ): _UpperCamelCase : Dict = output_channel _UpperCamelCase : List[Any] = block_out_channels[i] _UpperCamelCase : Any = i == len(lowerCamelCase__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": _UpperCamelCase : Any = FlaxCrossAttnDownBlockaD( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,num_attention_heads=num_attention_heads[i] ,add_downsample=not is_final_block ,use_linear_projection=self.use_linear_projection ,only_cross_attention=only_cross_attention[i] ,dtype=self.dtype ,) else: _UpperCamelCase : Dict = FlaxDownBlockaD( in_channels=lowerCamelCase__ ,out_channels=lowerCamelCase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,add_downsample=not is_final_block ,dtype=self.dtype ,) down_blocks.append(lowerCamelCase__ ) for _ in range(self.layers_per_block ): _UpperCamelCase : Any = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) if not is_final_block: _UpperCamelCase : List[Any] = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) controlnet_down_blocks.append(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = down_blocks _UpperCamelCase : List[str] = controlnet_down_blocks # mid _UpperCamelCase : Any = block_out_channels[-1] _UpperCamelCase : Tuple = FlaxUNetMidBlockaDCrossAttn( in_channels=lowerCamelCase__ ,dropout=self.dropout ,num_attention_heads=num_attention_heads[-1] ,use_linear_projection=self.use_linear_projection ,dtype=self.dtype ,) _UpperCamelCase : Any = nn.Conv( lowerCamelCase__ ,kernel_size=(1, 1) ,padding='VALID' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,) def __call__( self : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ,lowerCamelCase__ : str ,lowerCamelCase__ : float = 1.0 ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : bool = False ,): '''simple docstring''' _UpperCamelCase : Any = self.controlnet_conditioning_channel_order if channel_order == "bgr": _UpperCamelCase : Optional[Any] = jnp.flip(lowerCamelCase__ ,axis=1 ) # 1. time if not isinstance(lowerCamelCase__ ,jnp.ndarray ): _UpperCamelCase : Tuple = jnp.array([timesteps] ,dtype=jnp.intaa ) elif isinstance(lowerCamelCase__ ,jnp.ndarray ) and len(timesteps.shape ) == 0: _UpperCamelCase : Optional[Any] = timesteps.astype(dtype=jnp.floataa ) _UpperCamelCase : List[str] = jnp.expand_dims(lowerCamelCase__ ,0 ) _UpperCamelCase : Any = self.time_proj(lowerCamelCase__ ) _UpperCamelCase : Dict = self.time_embedding(lowerCamelCase__ ) # 2. pre-process _UpperCamelCase : List[Any] = jnp.transpose(lowerCamelCase__ ,(0, 2, 3, 1) ) _UpperCamelCase : Optional[int] = self.conv_in(lowerCamelCase__ ) _UpperCamelCase : Optional[int] = jnp.transpose(lowerCamelCase__ ,(0, 2, 3, 1) ) _UpperCamelCase : Tuple = self.controlnet_cond_embedding(lowerCamelCase__ ) sample += controlnet_cond # 3. down _UpperCamelCase : Any = (sample,) for down_block in self.down_blocks: if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): _UpperCamelCase , _UpperCamelCase : Union[str, Any] = down_block(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) else: _UpperCamelCase , _UpperCamelCase : str = down_block(lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) down_block_res_samples += res_samples # 4. mid _UpperCamelCase : Optional[int] = self.mid_block(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,deterministic=not train ) # 5. contronet blocks _UpperCamelCase : Union[str, Any] = () for down_block_res_sample, controlnet_block in zip(lowerCamelCase__ ,self.controlnet_down_blocks ): _UpperCamelCase : List[str] = controlnet_block(lowerCamelCase__ ) controlnet_down_block_res_samples += (down_block_res_sample,) _UpperCamelCase : Optional[int] = controlnet_down_block_res_samples _UpperCamelCase : Tuple = self.controlnet_mid_block(lowerCamelCase__ ) # 6. scaling _UpperCamelCase : Dict = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=lowerCamelCase__ ,mid_block_res_sample=lowerCamelCase__ )
83
from math import sqrt def A_ ( _lowerCAmelCase ) -> bool: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" UpperCamelCase : List[Any] = True # 0 and 1 are none primes. if number <= 1: UpperCamelCase : List[Any] = False for divisor in range(2 , int(round(sqrt(_lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCamelCase : Union[str, Any] = False break # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'status' must been from type bool" return status def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCamelCase : int = list(range(2 , n + 1 ) ) UpperCamelCase : Optional[int] = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_lowerCAmelCase ) ): for j in range(i + 1 , len(_lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCamelCase : Tuple = 0 # filters actual prime numbers. UpperCamelCase : str = [x for x in begin_list if x != 0] # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" UpperCamelCase : str = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(_lowerCAmelCase ): ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" UpperCamelCase : Optional[Any] = [] # this list will be returns of the function. # potential prime number factors. UpperCamelCase : Tuple = 2 UpperCamelCase : str = number if number == 0 or number == 1: ans.append(_lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_lowerCAmelCase ): while quotient != 1: if is_prime(_lowerCAmelCase ) and (quotient % factor == 0): ans.append(_lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type list" return ans def A_ ( _lowerCAmelCase ) -> Any: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Any = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = max(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Union[str, Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase : List[Any] = 0 # prime factorization of 'number' UpperCamelCase : Dict = prime_factorization(_lowerCAmelCase ) UpperCamelCase : List[Any] = min(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'ans' must been from type int" return ans def A_ ( _lowerCAmelCase ) -> Optional[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def A_ ( _lowerCAmelCase ) -> List[Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , _lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def A_ ( _lowerCAmelCase ) -> Any: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (number > 2) and is_even(_lowerCAmelCase ) ), "'number' must been an int, even and > 2" UpperCamelCase : List[str] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCamelCase : Dict = get_prime_numbers(_lowerCAmelCase ) UpperCamelCase : Tuple = len(_lowerCAmelCase ) # run variable for while-loops. UpperCamelCase : Optional[int] = 0 UpperCamelCase : int = None # exit variable. for break up the loops UpperCamelCase : Union[str, Any] = True while i < len_pn and loop: UpperCamelCase : Tuple = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCamelCase : Any = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (len(_lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Tuple = 0 while numbera != 0: UpperCamelCase : Tuple = numbera % numbera UpperCamelCase : Any = numbera UpperCamelCase : Union[str, Any] = rest # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCamelCase : Optional[int] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCamelCase : List[Any] = prime_factorization(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = prime_factorization(_lowerCAmelCase ) elif numbera == 1 or numbera == 1: UpperCamelCase : Optional[Any] = [] UpperCamelCase : int = [] UpperCamelCase : List[Any] = max(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 UpperCamelCase : List[str] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) UpperCamelCase : Tuple = prime_fac_a.count(_lowerCAmelCase ) for _ in range(max(_lowerCAmelCase , _lowerCAmelCase ) ): ans *= n else: UpperCamelCase : str = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCamelCase : Any = prime_fac_a.count(_lowerCAmelCase ) for _ in range(_lowerCAmelCase ): ans *= n done.append(_lowerCAmelCase ) # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" UpperCamelCase : int = 0 UpperCamelCase : int = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_lowerCAmelCase ): ans += 1 # precondition assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and is_prime( _lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> int: assert ( is_prime(_lowerCAmelCase ) and is_prime(_lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCamelCase : str = p_number_a + 1 # jump to the next number UpperCamelCase : Dict = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(_lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_lowerCAmelCase ): number += 1 # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ans[0] != p_number_a and ans[len(_lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def A_ ( _lowerCAmelCase ) -> List[str]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" UpperCamelCase : Dict = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(_lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def A_ ( _lowerCAmelCase ) -> int: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCamelCase : int = get_divisors(_lowerCAmelCase ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(_lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCamelCase : List[str] = gcd(abs(_lowerCAmelCase ) , abs(_lowerCAmelCase ) ) # precondition assert ( isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def A_ ( _lowerCAmelCase ) -> Dict: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" UpperCamelCase : str = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def A_ ( _lowerCAmelCase ) -> Tuple: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" UpperCamelCase : Dict = 0 UpperCamelCase : Dict = 1 UpperCamelCase : Union[str, Any] = 1 # this will be return for _ in range(n - 1 ): UpperCamelCase : Any = ans ans += fiba UpperCamelCase : str = tmp return ans
52
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :Any = "ctrl" UpperCAmelCase_ :str = ["past_key_values"] UpperCAmelCase_ :Any = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , __A=24_6534 , __A=256 , __A=1280 , __A=8192 , __A=48 , __A=16 , __A=0.1 , __A=0.1 , __A=1E-6 , __A=0.0_2 , __A=True , **__A , ) -> str: lowerCAmelCase_ :Optional[Any] = vocab_size lowerCAmelCase_ :str = n_positions lowerCAmelCase_ :int = n_embd lowerCAmelCase_ :int = n_layer lowerCAmelCase_ :Any = n_head lowerCAmelCase_ :Any = dff lowerCAmelCase_ :Optional[int] = resid_pdrop lowerCAmelCase_ :Optional[int] = embd_pdrop lowerCAmelCase_ :Any = layer_norm_epsilon lowerCAmelCase_ :Any = initializer_range lowerCAmelCase_ :Optional[Any] = use_cache super().__init__(**__A )
84
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 : str = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. __lowerCamelCase : Tuple = direct_transformers_import(PATH_TO_TRANSFORMERS) __lowerCamelCase : List[str] = 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 : Optional[Any] = re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""") __lowerCamelCase : List[str] = { """DecisionTransformerConfig""", """EncoderDecoderConfig""", """MusicgenConfig""", """RagConfig""", """SpeechEncoderDecoderConfig""", """TimmBackboneConfig""", """VisionEncoderDecoderConfig""", """VisionTextDualEncoderConfig""", """LlamaConfig""", } def A_ ( _lowerCAmelCase ) -> List[str]: UpperCamelCase : Optional[Any] = None # source code of `config_class` UpperCamelCase : Tuple = inspect.getsource(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = _re_checkpoint.findall(_lowerCAmelCase ) # 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 : Dict = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase : Any = F"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: UpperCamelCase : List[Any] = ckpt_name break return checkpoint def A_ ( ) -> List[str]: UpperCamelCase : Optional[int] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCamelCase : Union[str, Any] = get_checkpoint_from_config_class(_lowerCAmelCase ) UpperCamelCase : Optional[int] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Any = "\n".join(sorted(_lowerCAmelCase ) ) raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
52
0
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case ( lowercase_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = relative_attention snake_case_ = position_biased_input snake_case_ = pos_att_type snake_case_ = scope def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.get_config() snake_case_ = 300 return config def lowerCAmelCase__ ( self , a__ ) -> List[str]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForSequenceClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model( a__ , attention_mask=a__ , token_type_ids=a__ , start_positions=a__ , end_positions=a__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[int] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ : Dict = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ : Optional[int] = True lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Tuple = False lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Tuple = False def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = DebertaModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) @slow def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = DebertaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaModel.from_pretrained("microsoft/deberta-base" ) snake_case_ = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) snake_case_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. snake_case_ = torch.tensor( [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F'{output[:, 1:4, 1:4]}' )
85
from __future__ import annotations from functools import lru_cache from math import ceil __lowerCamelCase : str = 100 __lowerCamelCase : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __lowerCamelCase : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def A_ ( _lowerCAmelCase ) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} UpperCamelCase : set[int] = set() UpperCamelCase : int UpperCamelCase : int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A_ ( _lowerCAmelCase = 5000 ) -> int | None: for number_to_partition in range(1 , _lowerCAmelCase ): if len(partition(_lowerCAmelCase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
52
0
"""simple docstring""" import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 lowerCamelCase__ = data_utils.TransfoXLTokenizer lowerCamelCase__ = data_utils.TransfoXLCorpus lowerCamelCase__ = data_utils lowerCamelCase__ = data_utils def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(_UpperCamelCase , 'rb' ) as fp: __lowerCAmelCase : Dict = pickle.load(_UpperCamelCase , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) __lowerCAmelCase : Union[str, Any] = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F"Save vocabulary to {pytorch_vocab_dump_path}" ) __lowerCAmelCase : Optional[int] = corpus.vocab.__dict__ torch.save(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : Tuple = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , _UpperCamelCase ) __lowerCAmelCase : Tuple = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F"Save dataset to {pytorch_dataset_dump_path}" ) torch.save(_UpperCamelCase , _UpperCamelCase ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model __lowerCAmelCase : str = os.path.abspath(_UpperCamelCase ) __lowerCAmelCase : Any = os.path.abspath(_UpperCamelCase ) print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}." ) # Initialise PyTorch model if transfo_xl_config_file == "": __lowerCAmelCase : List[Any] = TransfoXLConfig() else: __lowerCAmelCase : List[Any] = TransfoXLConfig.from_json_file(_UpperCamelCase ) print(F"Building PyTorch model from configuration: {config}" ) __lowerCAmelCase : Union[str, Any] = TransfoXLLMHeadModel(_UpperCamelCase ) __lowerCAmelCase : Tuple = load_tf_weights_in_transfo_xl(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Save pytorch-model __lowerCAmelCase : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : Union[str, Any] = os.path.join(_UpperCamelCase , _UpperCamelCase ) print(F"Save PyTorch model to {os.path.abspath(_UpperCamelCase )}" ) torch.save(model.state_dict() , _UpperCamelCase ) print(F"Save configuration file to {os.path.abspath(_UpperCamelCase )}" ) with open(_UpperCamelCase , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--tf_checkpoint_path""", default="""""", type=str, help="""An optional path to a TensorFlow checkpoint path to be converted.""", ) parser.add_argument( """--transfo_xl_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--transfo_xl_dataset_file""", default="""""", type=str, help="""An optional dataset file to be converted in a vocabulary.""", ) lowerCamelCase__ = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
86
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Optional[int] = int(_lowerCAmelCase ) if decimal in (0, 1): # Exit cases for the recursion return str(_lowerCAmelCase ) UpperCamelCase , UpperCamelCase : Dict = divmod(_lowerCAmelCase , 2 ) return binary_recursive(_lowerCAmelCase ) + str(_lowerCAmelCase ) def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = str(_lowerCAmelCase ).strip() if not number: raise ValueError("No input value was provided" ) UpperCamelCase : Optional[int] = "-" if number.startswith("-" ) else "" UpperCamelCase : Any = number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return F"""{negative}0b{binary_recursive(int(_lowerCAmelCase ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
52
0
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, 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(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(__A ) class snake_case_ ( __A ): def __init__( self : List[Any] , **lowercase_ : Union[str, Any] ) -> Tuple: super().__init__(**lowercase_ ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self : Optional[int] , lowercase_ : Union[str, List[str], "Image", List["Image"]] , **lowercase_ : str ) -> Optional[int]: return super().__call__(lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : Any , **lowercase_ : Tuple ) -> Optional[Any]: lowercase__ : List[Any] = {} if "candidate_labels" in kwargs: lowercase__ : int = kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowercase__ : Dict = kwargs["hypothesis_template"] return preprocess_params, {}, {} def __UpperCamelCase ( self : str , lowercase_ : List[Any] , lowercase_ : Tuple=None , lowercase_ : List[str]="This is a photo of {}." ) -> Tuple: lowercase__ : str = load_image(lowercase_ ) lowercase__ : List[Any] = self.image_processor(images=[image] , return_tensors=self.framework ) lowercase__ : Optional[int] = candidate_labels lowercase__ : Optional[Any] = [hypothesis_template.format(lowercase_ ) for x in candidate_labels] lowercase__ : Union[str, Any] = self.tokenizer(lowercase_ , return_tensors=self.framework , padding=lowercase_ ) lowercase__ : int = [text_inputs] return inputs def __UpperCamelCase ( self : Dict , lowercase_ : List[Any] ) -> Optional[int]: lowercase__ : Tuple = model_inputs.pop("candidate_labels" ) lowercase__ : List[Any] = model_inputs.pop("text_inputs" ) if isinstance(text_inputs[0] , lowercase_ ): lowercase__ : List[str] = text_inputs[0] else: # Batching case. lowercase__ : Any = text_inputs[0][0] lowercase__ : List[str] = self.model(**lowercase_ , **lowercase_ ) lowercase__ : str = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def __UpperCamelCase ( self : str , lowercase_ : int ) -> List[Any]: lowercase__ : Any = model_outputs.pop("candidate_labels" ) lowercase__ : Tuple = model_outputs["logits"][0] if self.framework == "pt": lowercase__ : List[str] = logits.softmax(dim=-1 ).squeeze(-1 ) lowercase__ : str = probs.tolist() if not isinstance(lowercase_ , lowercase_ ): lowercase__ : Union[str, Any] = [scores] elif self.framework == "tf": lowercase__ : Optional[Any] = stable_softmax(lowercase_ , axis=-1 ) lowercase__ : List[Any] = probs.numpy().tolist() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) lowercase__ : Optional[Any] = [ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(lowercase_ , lowercase_ ) , key=lambda lowercase_ : -x[0] ) ] return result
87
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=24 , A_=2 , A_=6 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=None , A_=1000 , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : Dict = seq_length UpperCamelCase : Tuple = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : Optional[Any] = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : Optional[int] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : Optional[int] = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Optional[int] = scope UpperCamelCase : int = range_bbox def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase : Union[str, Any] = bbox[i, j, 3] UpperCamelCase : int = bbox[i, j, 1] UpperCamelCase : int = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : List[str] = bbox[i, j, 2] UpperCamelCase : Optional[int] = bbox[i, j, 0] UpperCamelCase : Optional[Any] = t UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : str = None if self.use_token_type_ids: UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Dict = None UpperCamelCase : int = None if self.use_labels: UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __UpperCamelCase( self ): '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = LiltModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = model(A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ ) UpperCamelCase : Optional[int] = model(A_ , bbox=A_ , token_type_ids=A_ ) UpperCamelCase : Any = model(A_ , bbox=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = self.num_labels UpperCamelCase : Dict = LiltForTokenClassification(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Dict = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Dict = LiltForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model( A_ , bbox=A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Tuple = config_and_inputs UpperCamelCase : Tuple = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) _UpperCAmelCase :Optional[Any] = ( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) _UpperCAmelCase :Dict = False _UpperCAmelCase :Union[str, Any] = False def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' return True def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = LiltModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = LiltModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @slow class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base" ).to(A_ ) UpperCamelCase : Tuple = torch.tensor([[1, 2]] , device=A_ ) UpperCamelCase : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=A_ ) # forward pass with torch.no_grad(): UpperCamelCase : Optional[int] = model(input_ids=A_ , bbox=A_ ) UpperCamelCase : List[str] = torch.Size([1, 2, 768] ) UpperCamelCase : Any = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=A_ , ) self.assertTrue(outputs.last_hidden_state.shape , A_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , A_ , atol=1e-3 ) )
52
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(_A ) , """Tatoeba directory does not exist.""" ) class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _lowercase ( self : Tuple ) -> Optional[int]: """simple docstring""" __magic_name__ = tempfile.mkdtemp() return TatoebaConverter(save_dir=UpperCamelCase__ ) @slow def _lowercase ( self : Tuple ) -> List[str]: """simple docstring""" self.resolver.convert_models(["""heb-eng"""] ) @slow def _lowercase ( self : int ) -> Tuple: """simple docstring""" __magic_name__ , __magic_name__ = self.resolver.write_model_card("""opus-mt-he-en""" , dry_run=UpperCamelCase__ ) assert mmeta["long_pair"] == "heb-eng"
88
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __lowerCamelCase : Union[str, Any] = pytest.mark.integration @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_ ) for x in np.arange(30 ).tolist()]} ) return dset def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() UpperCamelCase : List[Any] = dset.map( lambda A_ , A_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=A_ , keep_in_memory=A_ ) UpperCamelCase : List[str] = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase , UpperCamelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCamelCase , UpperCamelCase : int = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A_ , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch UpperCamelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} UpperCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=A_ ) UpperCamelCase , UpperCamelCase : List[str] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Optional[int] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCamelCase : Any = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[Any] = 1 UpperCamelCase , UpperCamelCase : Optional[Any] = index.search(A_ ) self.assertRaises(A_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCamelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCamelCase , UpperCamelCase : Tuple = index.search_batch(A_ ) self.assertRaises(A_ , index.search_batch , queries[0] ) UpperCamelCase : Optional[int] = [scores[0] for scores in total_scores] UpperCamelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCamelCase : List[str] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(A_ ): UpperCamelCase : List[str] = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : Dict = faiss.IndexFlat(5 ) UpperCamelCase : Union[str, Any] = FaissIndex(custom_index=A_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __UpperCamelCase( self ): '''simple docstring''' import faiss UpperCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A_ ) as tmp_file: index.save(tmp_file.name ) UpperCamelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCamelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : int = 1 UpperCamelCase , UpperCamelCase : Dict = index.search(A_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def A_ ( _lowerCAmelCase ) -> Optional[int]: import faiss UpperCamelCase : Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCamelCase : List[Any] = "index.faiss" UpperCamelCase : List[str] = F"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCamelCase : List[str] = np.zeros(5 , dtype=np.floataa ) UpperCamelCase : Optional[int] = 1 UpperCamelCase , UpperCamelCase : List[str] = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __snake_case ): def __UpperCamelCase( self ): '''simple docstring''' from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: UpperCamelCase : List[str] = Elasticsearch() UpperCamelCase : Union[str, Any] = {"acknowledged": True} UpperCamelCase : Union[str, Any] = ElasticSearchIndex(es_client=A_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query UpperCamelCase : str = "foo" UpperCamelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : Tuple = index.search(A_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCamelCase : Dict = "foo" UpperCamelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} UpperCamelCase , UpperCamelCase : str = index.search(A_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCamelCase : Dict = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Optional[int] = index.search_batch(A_ ) UpperCamelCase : str = [scores[0] for scores in total_scores] UpperCamelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ ) # batched queries with timeout UpperCamelCase : int = ["foo", "bar", "foobar"] UpperCamelCase : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} UpperCamelCase , UpperCamelCase : Union[str, Any] = index.search_batch(A_ , request_timeout=30 ) UpperCamelCase : Union[str, Any] = [scores[0] for scores in total_scores] UpperCamelCase : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(A_ ) , 0 ) self.assertListEqual([1, 1, 1] , A_ )
52
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FocalNetForImageClassification''', '''FocalNetForMaskedImageModeling''', '''FocalNetBackbone''', '''FocalNetModel''', '''FocalNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
def A_ ( _lowerCAmelCase = 50 ) -> int: UpperCamelCase : List[Any] = [[0] * 3 for _ in range(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 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
52
0
import sys from collections import defaultdict class __lowerCAmelCase : """simple docstring""" def __init__( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = [] def lowercase_ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' return self.node_position[vertex] def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = pos def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: '''simple docstring''' if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCamelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCamelCase = 2 * start + 1 else: __lowerCamelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCamelCase , __lowerCamelCase = heap[smallest_child], positions[smallest_child] __lowerCamelCase , __lowerCamelCase = ( heap[start], positions[start], ) __lowerCamelCase , __lowerCamelCase = temp, tempa __lowerCamelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , lowerCamelCase__ ) self.top_to_bottom(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = position[index] while index != 0: __lowerCamelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCamelCase = heap[parent] __lowerCamelCase = position[parent] self.set_position(position[parent] , lowerCamelCase__ ) else: __lowerCamelCase = val __lowerCamelCase = temp self.set_position(lowerCamelCase__ , lowerCamelCase__ ) break __lowerCamelCase = parent else: __lowerCamelCase = val __lowerCamelCase = temp self.set_position(lowerCamelCase__ , 0 ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: '''simple docstring''' __lowerCamelCase = len(lowerCamelCase__ ) // 2 - 1 for i in range(lowerCamelCase__ , -1 , -1 ): self.top_to_bottom(lowerCamelCase__ , lowerCamelCase__ , len(lowerCamelCase__ ) , lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> Any: '''simple docstring''' __lowerCamelCase = positions[0] __lowerCamelCase = sys.maxsize self.top_to_bottom(lowerCamelCase__ , 0 , len(lowerCamelCase__ ) , lowerCamelCase__ ) return temp def lowerCamelCase_ ( UpperCamelCase__ : str ) -> List[str]: """simple docstring""" __lowerCamelCase = Heap() __lowerCamelCase = [0] * len(UpperCamelCase__ ) __lowerCamelCase = [-1] * len(UpperCamelCase__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCamelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCamelCase = [] for vertex in range(len(UpperCamelCase__ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase__ ) heap.node_position.append(UpperCamelCase__ ) __lowerCamelCase = [] __lowerCamelCase = 1 __lowerCamelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCamelCase = 0 __lowerCamelCase = distance heap.heapify(UpperCamelCase__ , UpperCamelCase__ ) for _ in range(1 , len(UpperCamelCase__ ) ): __lowerCamelCase = heap.delete_minimum(UpperCamelCase__ , UpperCamelCase__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCamelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase__ )] ): __lowerCamelCase = distance heap.bottom_to_top( UpperCamelCase__ , heap.get_position(UpperCamelCase__ ) , UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > __A = int(input("Enter number of edges: ").strip()) __A = defaultdict(list) for _ in range(edges_number): __A = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
90
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : List[Any] = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def A_ ( _lowerCAmelCase ) -> dict[str, str]: UpperCamelCase : Optional[Any] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key UpperCamelCase : Tuple = remove_duplicates(key.upper() ) UpperCamelCase : int = len(_lowerCAmelCase ) # First fill cipher with key characters UpperCamelCase : int = {alphabet[i]: char for i, char in enumerate(_lowerCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_lowerCAmelCase ) , 26 ): UpperCamelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase : List[str] = alphabet[i - offset] UpperCamelCase : List[Any] = char return cipher_alphabet def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: return "".join(cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Union[str, Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_lowerCAmelCase , _lowerCAmelCase ) for ch in message.upper() ) def A_ ( ) -> None: UpperCamelCase : int = input("Enter message to encode or decode: " ).strip() UpperCamelCase : str = input("Enter keyword: " ).strip() UpperCamelCase : Union[str, Any] = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: UpperCamelCase : List[str] = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) UpperCamelCase : str = create_cipher_map(_lowerCAmelCase ) print(func(_lowerCAmelCase , _lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
52
0
"""simple docstring""" UpperCAmelCase_ : Dict = range(2, 20 + 1) UpperCAmelCase_ : Union[str, Any] = [10**k for k in range(ks[-1] + 1)] UpperCAmelCase_ : dict[int, dict[int, list[list[int]]]] = {} def _A (__a , __a , __a , __a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = sum(a_i[j] for j in range(__a , len(__a ) ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = sum(a_i[j] * base[j] for j in range(min(len(__a ) , __a ) ) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0, 0 SCREAMING_SNAKE_CASE_ : str = n - i SCREAMING_SNAKE_CASE_ : Dict = memo.get(__a ) if sub_memo is not None: SCREAMING_SNAKE_CASE_ : str = sub_memo.get(__a ) if jumps is not None and len(__a ) > 0: # find and make the largest jump without going over SCREAMING_SNAKE_CASE_ : List[str] = -1 for _k in range(len(__a ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: SCREAMING_SNAKE_CASE_ : Optional[Any] = _k break if max_jump >= 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jumps[max_jump] # since the difference between jumps is cached, add c SCREAMING_SNAKE_CASE_ : Optional[Any] = diff + c for j in range(min(__a , len(__a ) ) ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = divmod(__a , 10 ) if new_c > 0: add(__a , __a , __a ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = [] else: SCREAMING_SNAKE_CASE_ : List[Any] = {c: []} SCREAMING_SNAKE_CASE_ : Optional[int] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = next_term(__a , k - 1 , i + dn , __a ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = compute(__a , __a , i + dn , __a ) diff += _diff dn += terms_jumped SCREAMING_SNAKE_CASE_ : List[str] = sub_memo[c] # keep jumps sorted by # of terms skipped SCREAMING_SNAKE_CASE_ : List[Any] = 0 while j < len(__a ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(__a , (diff, dn, k) ) return (diff, dn) def _A (__a , __a , __a , __a ) -> Optional[int]: """simple docstring""" if i >= n: return 0, i if k > len(__a ): a_i.extend([0 for _ in range(k - len(__a ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) SCREAMING_SNAKE_CASE_ : Any = i SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = 0, 0, 0 for j in range(len(__a ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 SCREAMING_SNAKE_CASE_ : Dict = ds_c + ds_b diff += addend SCREAMING_SNAKE_CASE_ : Tuple = 0 for j in range(__a ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = a_i[j] + addend SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(__a , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(__a , __a , __a ) return diff, i - start_i def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" for j in range(__a , len(__a ) ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = digits[j] + addend if s >= 10: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = divmod(__a , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = addend // 10 + quotient else: SCREAMING_SNAKE_CASE_ : Tuple = s SCREAMING_SNAKE_CASE_ : Tuple = addend // 10 if addend == 0: break while addend > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = divmod(__a , 10 ) digits.append(__a ) def _A (__a = 10**15 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [1] SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : Dict = 0 while True: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = next_term(__a , 20 , i + dn , __a ) dn += terms_jumped if dn == n - i: break SCREAMING_SNAKE_CASE_ : List[str] = 0 for j in range(len(__a ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
91
from sklearn.metrics import fa_score import datasets __lowerCamelCase : List[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ __lowerCamelCase : List[Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ __lowerCamelCase : str = """ @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 ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def __UpperCamelCase( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ): '''simple docstring''' UpperCamelCase : List[str] = fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
52
0
from __future__ import annotations import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : list[float] ): return np.maximum(0 , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
92
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = KandinskyInpaintPipeline _UpperCAmelCase :List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] _UpperCAmelCase :Dict = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] _UpperCAmelCase :Optional[int] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _UpperCAmelCase :int = False @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return 32 @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim @property def __UpperCamelCase( self ): '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCamelCase( self ): '''simple docstring''' return 100 @property def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : Optional[int] = MultilingualCLIP(A_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : Optional[int] = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase : List[Any] = UNetaDConditionModel(**A_ ) return model @property def __UpperCamelCase( self ): '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCamelCase( self ): '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.dummy_text_encoder UpperCamelCase : str = self.dummy_tokenizer UpperCamelCase : List[Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="epsilon" , thresholding=A_ , ) UpperCamelCase : Optional[Any] = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __UpperCamelCase( self , A_ , A_=0 ): '''simple docstring''' UpperCamelCase : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image UpperCamelCase : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(A_ ) ).convert("RGB" ).resize((256, 256) ) # create mask UpperCamelCase : str = np.ones((64, 64) , dtype=np.floataa ) UpperCamelCase : str = 0 if str(A_ ).startswith("mps" ): UpperCamelCase : int = torch.manual_seed(A_ ) else: UpperCamelCase : Tuple = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase : Union[str, Any] = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = "cpu" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**A_ ) UpperCamelCase : Tuple = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase : Any = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase : List[Any] = output.images UpperCamelCase : List[Any] = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase : List[Any] = image[0, -3:, -3:, -1] UpperCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) UpperCamelCase : Union[str, Any] = np.array( [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __UpperCamelCase( self ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) UpperCamelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) UpperCamelCase : Dict = np.ones((768, 768) , dtype=np.floataa ) UpperCamelCase : str = 0 UpperCamelCase : List[Any] = "a hat" UpperCamelCase : Tuple = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) UpperCamelCase : Optional[Any] = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[Any] = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() UpperCamelCase : Dict = pipeline( A_ , image=A_ , mask_image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
52
0
'''simple docstring''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin 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 _lowercase : List[str] = "platform" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , ): """simple docstring""" if attention_mask is None: lowercase_ : List[Any] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: lowercase_ : Any = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: lowercase_ : Dict = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase_ : str = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase_ : Union[str, Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowerCAmelCase__ : 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=16 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0.02 , ): """simple docstring""" lowercase_ : Optional[int] = parent lowercase_ : Tuple = batch_size lowercase_ : Tuple = seq_length lowercase_ : Optional[int] = is_training lowercase_ : Union[str, Any] = use_labels lowercase_ : int = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = num_hidden_layers lowercase_ : List[Any] = num_attention_heads lowercase_ : Optional[Any] = intermediate_size lowercase_ : str = hidden_act lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Dict = attention_probs_dropout_prob lowercase_ : Optional[Any] = max_position_embeddings lowercase_ : Any = eos_token_id lowercase_ : Optional[int] = pad_token_id lowercase_ : Dict = bos_token_id lowercase_ : Optional[int] = initializer_range def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) lowercase_ : Dict = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) lowercase_ : Optional[int] = shift_tokens_right(__SCREAMING_SNAKE_CASE , 1 , 2 ) lowercase_ : Union[str, Any] = BlenderbotConfig( 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[int] = prepare_blenderbot_inputs_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return config, inputs_dict def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : Any = self.prepare_config_and_inputs() return config, inputs_dict def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = 20 lowercase_ : Optional[Any] = model_class_name(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = model.encode(inputs_dict['''input_ids'''] ) lowercase_ , lowercase_ : List[Any] = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase_ : int = model.init_cache(decoder_input_ids.shape[0] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowercase_ : Optional[int] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase_ : Optional[int] = 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 , ) lowercase_ : int = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase_ : List[str] = 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 , ) lowercase_ : Tuple = model.decode(__SCREAMING_SNAKE_CASE , __SCREAMING_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 _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = 20 lowercase_ : Any = model_class_name(__SCREAMING_SNAKE_CASE ) lowercase_ : int = model.encode(inputs_dict['''input_ids'''] ) lowercase_ , lowercase_ : Tuple = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase_ : List[str] = 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] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[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[Any] = 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 , ) lowercase_ : int = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase_ : Dict = 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 , ) lowercase_ : int = model.decode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, 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}''' ) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): lowerCAmelCase_ = 9_9 def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) lowercase_ : str = input_ids.shape[0] lowercase_ : Tuple = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ , lowercase_ : List[Any] = self._get_config_and_data() lowercase_ : List[Any] = FlaxBlenderbotForConditionalGeneration(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = lm_model(input_ids=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) lowercase_ : Tuple = FlaxBlenderbotForConditionalGeneration(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) lowercase_ : Optional[int] = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) lowercase_ : Dict = lm_model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) lowercase_ : List[Any] = shift_tokens_right(__SCREAMING_SNAKE_CASE , 1 , 2 ) lowercase_ : Optional[int] = np.equal(__SCREAMING_SNAKE_CASE , 1 ).astype(np.floataa ).sum() lowercase_ : Tuple = np.equal(__SCREAMING_SNAKE_CASE , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(__SCREAMING_SNAKE_CASE , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase , lowerCamelCase_ ): lowerCAmelCase_ = True lowerCAmelCase_ = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) lowerCAmelCase_ = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = FlaxBlenderbotModelTester(self ) def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : Tuple = self.model_tester.prepare_config_and_inputs() 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 _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : Dict = self.model_tester.prepare_config_and_inputs() 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 _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase_ : Tuple = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 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''' ): lowercase_ : Tuple = encode_jitted(**__SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase_ : str = 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 _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : 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_ : Dict = model_class(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) lowercase_ : Optional[int] = { '''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''' ): lowercase_ : List[str] = decode_jitted(**__SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase_ : List[str] = 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 _snake_case ( self ): """simple docstring""" for model_class_name in self.all_model_classes: lowercase_ : List[Any] = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids lowercase_ : Optional[int] = np.ones((1, 1) ) * model.config.eos_token_id lowercase_ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : int = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} lowercase_ : int = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} lowercase_ : Dict = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) lowercase_ : Any = ['''Sam'''] lowercase_ : Optional[int] = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''jax''' ) lowercase_ : List[str] = model.generate(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : str = '''Sam is a great name. It means "sun" in Gaelic.''' lowercase_ : str = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) assert generated_txt[0].strip() == tgt_text
93
class A__ : def __init__( self , A_ ): '''simple docstring''' UpperCamelCase : Union[str, Any] = set_counts UpperCamelCase : int = max(A_ ) UpperCamelCase : Optional[Any] = len(A_ ) UpperCamelCase : Union[str, Any] = [1] * num_sets UpperCamelCase : Union[str, Any] = list(range(A_ ) ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = self.get_parent(A_ ) UpperCamelCase : Optional[int] = self.get_parent(A_ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] UpperCamelCase : int = 0 UpperCamelCase : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 UpperCamelCase : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] UpperCamelCase : Any = 0 UpperCamelCase : Optional[int] = src_parent UpperCamelCase : int = self.set_counts[src_parent] UpperCamelCase : Any = max(self.max_set , A_ ) return True def __UpperCamelCase( self , A_ ): '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set UpperCamelCase : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
52
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE__ ( *_lowerCamelCase , **_lowerCamelCase ): pass @is_pipeline_test @require_torch @require_vision class _snake_case ( unittest.TestCase ): SCREAMING_SNAKE_CASE__ = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): a :Optional[int] = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' ) a :Any = [ { '''image''': Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''question''': '''How many cats are there?''', }, { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''question''': '''How many cats are there?''', }, ] return vqa_pipeline, examples def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ): a :List[str] = vqa_pipeline(_lowerCamelCase , top_k=1 ) self.assertEqual( _lowerCamelCase , [ [{'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}], [{'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}], ] , ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ): a :Tuple = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' ) a :Tuple = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' a :List[str] = '''How many cats are there?''' a :Any = vqa_pipeline(image=_lowerCamelCase , question='''How many cats are there?''' , top_k=2 ) self.assertEqual( _lowerCamelCase , [{'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}, {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}] ) a :Dict = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( _lowerCamelCase , [{'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}, {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase )}] ) @slow @require_torch def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[Any] = pipeline('''visual-question-answering''' , model='''dandelin/vilt-b32-finetuned-vqa''' ) a :Dict = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' a :int = '''How many cats are there?''' a :Optional[int] = vqa_pipeline(image=_lowerCamelCase , question=_lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}] ) a :int = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}] ) a :Optional[Any] = vqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [[{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}]] * 2 , ) @require_tf @unittest.skip('''Visual question answering not implemented in TF''' ) def SCREAMING_SNAKE_CASE__ ( self ): pass
94
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase : Any = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : str = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """megatron-bert""" def __init__( self , lowerCAmelCase__=2_9_0_5_6 , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=2_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=4_0_9_6 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__="absolute" , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =vocab_size a__ : Any =hidden_size a__ : List[Any] =num_hidden_layers a__ : Optional[int] =num_attention_heads a__ : List[str] =hidden_act a__ : Union[str, Any] =intermediate_size a__ : Optional[int] =hidden_dropout_prob a__ : Tuple =attention_probs_dropout_prob a__ : List[str] =max_position_embeddings a__ : Optional[int] =type_vocab_size a__ : int =initializer_range a__ : Any =layer_norm_eps a__ : List[Any] =position_embedding_type a__ : Dict =use_cache
95
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : str = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class A__ ( __snake_case , __snake_case ): _UpperCAmelCase :Optional[int] = 'convnextv2' def __init__( self , A_=3 , A_=4 , A_=4 , A_=None , A_=None , A_="gelu" , A_=0.02 , A_=1e-12 , A_=0.0 , A_=224 , A_=None , A_=None , **A_ , ): '''simple docstring''' super().__init__(**A_ ) UpperCamelCase : Dict = num_channels UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Union[str, Any] = num_stages UpperCamelCase : List[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes UpperCamelCase : List[str] = [3, 3, 9, 3] if depths is None else depths UpperCamelCase : Dict = hidden_act UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : str = drop_path_rate UpperCamelCase : List[str] = image_size UpperCamelCase : List[str] = ["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase : str = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
52
0
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf lowercase__ = logging.get_logger(__name__) @dataclass class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lowerCamelCase__ = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **lowercase ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: _lowerCamelCase : Any = deprecated_arg[3:] _lowerCamelCase : int = not kwargs.pop(lowercase ) logger.warning( F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' F''' {positive_arg}={kwargs[positive_arg]}''' ) _lowerCamelCase : Any = kwargs.pop('tpu_name' , self.tpu_name ) _lowerCamelCase : Dict = kwargs.pop('device_idx' , self.device_idx ) _lowerCamelCase : int = kwargs.pop('eager_mode' , self.eager_mode ) _lowerCamelCase : List[str] = kwargs.pop('use_xla' , self.use_xla ) super().__init__(**lowercase ) lowerCamelCase__ = field( default=lowercase, metadata={"""help""": """Name of TPU"""}, ) lowerCamelCase__ = field( default=0, metadata={"""help""": """CPU / GPU device index. Defaults to 0."""}, ) lowerCamelCase__ = field(default=lowercase, metadata={"""help""": """Benchmark models in eager model."""} ) lowerCamelCase__ = field( default=lowercase, metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" }, ) @cached_property def A_ ( self ): requires_backends(self , ['tf'] ) _lowerCamelCase : int = None if self.tpu: try: if self.tpu_name: _lowerCamelCase : List[Any] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: _lowerCamelCase : str = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: _lowerCamelCase : List[str] = None return tpu @cached_property def A_ ( self ): requires_backends(self , ['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) _lowerCamelCase : Any = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , 'GPU' ) _lowerCamelCase : Dict = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , 'GPU' ) # disable GPU _lowerCamelCase : int = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' ) return strategy @property def A_ ( self ): requires_backends(self , ['tf'] ) return self._setup_tpu is not None @property def A_ ( self ): requires_backends(self , ['tf'] ) return self._setup_strategy @property def A_ ( self ): requires_backends(self , ['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def A_ ( self ): requires_backends(self , ['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def A_ ( self ): return self.n_gpu > 0
96
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def A_ ( ) -> List[Any]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_lowerCAmelCase ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def A_ ( ) -> Tuple: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def A_ ( ) -> Optional[int]: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_lowerCAmelCase ): http_head("https://huggingface.co" )
52
0
'''simple docstring''' 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 lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_=7 , UpperCamelCase_=3 , UpperCamelCase_=18 , UpperCamelCase_=30 , UpperCamelCase_=400 , UpperCamelCase_=True , UpperCamelCase_=None , UpperCamelCase_=True , ): '''simple docstring''' UpperCamelCase__ :Any = size if size is not None else {'''height''': 18, '''width''': 18} UpperCamelCase__ :Union[str, Any] = parent UpperCamelCase__ :Tuple = batch_size UpperCamelCase__ :int = num_channels UpperCamelCase__ :Optional[Any] = image_size UpperCamelCase__ :List[str] = min_resolution UpperCamelCase__ :Optional[int] = max_resolution UpperCamelCase__ :Optional[Any] = do_resize UpperCamelCase__ :Optional[int] = size UpperCamelCase__ :List[Any] = apply_ocr def lowerCAmelCase__ ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowercase ( A__ , unittest.TestCase ): """simple docstring""" _a = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :List[Any] = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCamelCase_ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCamelCase_ , '''size''' ) ) self.assertTrue(hasattr(UpperCamelCase_ , '''apply_ocr''' ) ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) UpperCamelCase__ :Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase__ ( self ): '''simple docstring''' pass def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ :Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase_ , Image.Image ) # Test not batched input UpperCamelCase__ :List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCamelCase_ ) self.assertIsInstance(encoding.boxes , UpperCamelCase_ ) # Test batched UpperCamelCase__ :int = image_processing(UpperCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ , numpify=UpperCamelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase_ , np.ndarray ) # Test not batched input UpperCamelCase__ :Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched UpperCamelCase__ :Tuple = image_processing(UpperCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase__ :List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ , torchify=UpperCamelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase_ , torch.Tensor ) # Test not batched input UpperCamelCase__ :Union[str, Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched UpperCamelCase__ :Dict = image_processing(UpperCamelCase_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = LayoutLMvaImageProcessor() from datasets import load_dataset UpperCamelCase__ :int = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) UpperCamelCase__ :int = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) UpperCamelCase__ :str = image_processing(UpperCamelCase_ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 UpperCamelCase__ :Tuple = [['''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__ :Dict = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCamelCase_ ) self.assertListEqual(encoding.boxes , UpperCamelCase_ ) # with apply_OCR = False UpperCamelCase__ :List[str] = LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase_ ) UpperCamelCase__ :Tuple = image_processing(UpperCamelCase_ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
97
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
0
"""simple docstring""" def a_ ( lowerCamelCase = 1_0**1_2 ): UpperCAmelCase__ = 1 UpperCAmelCase__ = 0 UpperCAmelCase__ = 1 UpperCAmelCase__ = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(F"""{solution() = }""")
98
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __lowerCamelCase : List[Any] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ __lowerCamelCase : Optional[int] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ __lowerCamelCase : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def A_ ( _lowerCAmelCase ) -> str: def remove_articles(_lowerCAmelCase ): UpperCamelCase : Tuple = re.compile(r"\b(a|an|the)\b" , re.UNICODE ) return re.sub(_lowerCAmelCase , " " , _lowerCAmelCase ) def white_space_fix(_lowerCAmelCase ): return " ".join(text.split() ) def remove_punc(_lowerCAmelCase ): UpperCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_lowerCAmelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: return int(normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = [any(compute_exact(_lowerCAmelCase , _lowerCAmelCase ) for ref in refs ) for pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase )] return (sum(_lowerCAmelCase ) / len(_lowerCAmelCase )) * 100 def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Optional[int] = Counter(_lowerCAmelCase ) UpperCamelCase : List[Any] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : Tuple = scount * numref UpperCamelCase : Union[str, Any] = Counter(_lowerCAmelCase ) UpperCamelCase : Tuple = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Dict = ccount * numref # KEEP UpperCamelCase : List[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Union[str, Any] = keepgramcounter_rep & rgramcounter UpperCamelCase : Dict = sgramcounter_rep & rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Any = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = keeptmpscorea / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Union[str, Any] = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : Any = sgramcounter_rep - cgramcounter_rep UpperCamelCase : str = delgramcounter_rep - rgramcounter UpperCamelCase : Any = sgramcounter_rep - rgramcounter UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Dict = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : str = deltmpscorea / len(_lowerCAmelCase ) # ADDITION UpperCamelCase : List[str] = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : List[str] = set(_lowerCAmelCase ) & set(_lowerCAmelCase ) UpperCamelCase : Dict = set(_lowerCAmelCase ) - set(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 UpperCamelCase : Tuple = 1 if len(_lowerCAmelCase ) > 0: UpperCamelCase : Dict = addtmpscore / len(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: UpperCamelCase : Tuple = addtmpscore / len(_lowerCAmelCase ) UpperCamelCase : List[str] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : List[str] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: UpperCamelCase : int = len(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = ssent.split(" " ) UpperCamelCase : Dict = csent.split(" " ) UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Any = [] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : str = [] UpperCamelCase : str = [] UpperCamelCase : Dict = [] UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = [] for rsent in rsents: UpperCamelCase : List[Any] = rsent.split(" " ) UpperCamelCase : List[str] = [] UpperCamelCase : int = [] UpperCamelCase : Tuple = [] ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Dict = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : List[Any] = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) ragramslist.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = sagrams[i] + " " + sagrams[i + 1] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : List[str] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Optional[int] = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(_lowerCAmelCase ) for i in range(0 , len(_lowerCAmelCase ) - 1 ): if i < len(_lowerCAmelCase ) - 1: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(_lowerCAmelCase ) if i < len(_lowerCAmelCase ) - 3: UpperCamelCase : Union[str, Any] = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(_lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = SARIngram(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : str = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : Union[str, Any] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Union[str, Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = "13a" , _lowerCAmelCase = True ) -> Optional[Any]: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : Dict = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : str = sacrebleu.metrics.bleu._get_tokenizer(_lowerCAmelCase )()(_lowerCAmelCase ) else: UpperCamelCase : Dict = sacrebleu.TOKENIZERS[tokenizer]()(_lowerCAmelCase ) elif tokenizer == "moses": UpperCamelCase : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase , escape=_lowerCAmelCase ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(_lowerCAmelCase , return_str=_lowerCAmelCase ) else: UpperCamelCase : Union[str, Any] = sentence if not return_str: UpperCamelCase : Tuple = normalized_sent.split() return normalized_sent def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: if not (len(_lowerCAmelCase ) == len(_lowerCAmelCase ) == len(_lowerCAmelCase )): raise ValueError("Sources length must match predictions and references lengths." ) UpperCamelCase : Optional[Any] = 0 for src, pred, refs in zip(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): sari_score += SARIsent(normalize(_lowerCAmelCase ) , normalize(_lowerCAmelCase ) , [normalize(_lowerCAmelCase ) for sent in refs] ) UpperCamelCase : Optional[int] = sari_score / len(_lowerCAmelCase ) return 100 * sari_score def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase="exp" , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> List[str]: UpperCamelCase : Optional[Any] = len(references[0] ) if any(len(_lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(_lowerCAmelCase )] UpperCamelCase : Tuple = sacrebleu.corpus_bleu( _lowerCAmelCase , _lowerCAmelCase , smooth_method=_lowerCAmelCase , smooth_value=_lowerCAmelCase , force=_lowerCAmelCase , lowercase=_lowerCAmelCase , use_effective_order=_lowerCAmelCase , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCamelCase( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = {} result.update({"sari": compute_sari(sources=A_ , predictions=A_ , references=A_ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=A_ , references=A_ )} ) result.update({"exact": compute_em(predictions=A_ , references=A_ )} ) return result
52
0
import argparse import collections import json import os import re import string import sys import numpy as np lowercase : Union[str, Any] = re.compile(r"""\b(a|an|the)\b""", re.UNICODE) lowercase : Union[str, Any] = None def A_ ( ) -> Dict: a__ : Dict = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' ) parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.' ) parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.' ) parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).' ) parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.' ) parser.add_argument( '--na-prob-thresh' , '-t' , type=A__ , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=A__ , help='Save precision-recall curves to directory.' ) parser.add_argument('--verbose' , '-v' , action='store_true' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def A_ ( A__ ) -> int: a__ : Any = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a__ : Optional[int] = bool(qa['answers']['text'] ) return qid_to_has_ans def A_ ( A__ ) -> List[Any]: def remove_articles(A__ ): return ARTICLES_REGEX.sub(' ' , A__ ) def white_space_fix(A__ ): return " ".join(text.split() ) def remove_punc(A__ ): a__ : Optional[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A__ ) ) ) ) def A_ ( A__ ) -> Union[str, Any]: if not s: return [] return normalize_answer(A__ ).split() def A_ ( A__ , A__ ) -> Optional[Any]: return int(normalize_answer(A__ ) == normalize_answer(A__ ) ) def A_ ( A__ , A__ ) -> Any: a__ : Tuple = get_tokens(A__ ) a__ : Optional[int] = get_tokens(A__ ) a__ : int = collections.Counter(A__ ) & collections.Counter(A__ ) a__ : Optional[Any] = sum(common.values() ) if len(A__ ) == 0 or len(A__ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 a__ : int = 1.0 * num_same / len(A__ ) a__ : List[Any] = 1.0 * num_same / len(A__ ) a__ : Tuple = (2 * precision * recall) / (precision + recall) return fa def A_ ( A__ , A__ ) -> Any: a__ : Tuple = {} a__ : int = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a__ : Optional[int] = qa['id'] a__ : Any = [t for t in qa['answers']['text'] if normalize_answer(A__ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string a__ : List[str] = [''] if qid not in preds: print(F'Missing prediction for {qid}' ) continue a__ : Union[str, Any] = preds[qid] # Take max over all gold answers a__ : Tuple = max(compute_exact(A__ , A__ ) for a in gold_answers ) a__ : List[Any] = max(compute_fa(A__ , A__ ) for a in gold_answers ) return exact_scores, fa_scores def A_ ( A__ , A__ , A__ , A__ ) -> Tuple: a__ : List[Any] = {} for qid, s in scores.items(): a__ : Tuple = na_probs[qid] > na_prob_thresh if pred_na: a__ : str = float(not qid_to_has_ans[qid] ) else: a__ : int = s return new_scores def A_ ( A__ , A__ , A__=None ) -> List[Any]: if not qid_list: a__ : str = len(A__ ) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values() ) / total), ('f1', 1_00.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: a__ : int = len(A__ ) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list ) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list ) / total), ('total', total), ] ) def A_ ( A__ , A__ , A__ ) -> Optional[int]: for k in new_eval: a__ : Optional[int] = new_eval[k] def A_ ( A__ , A__ , A__ , A__ ) -> Union[str, Any]: plt.step(A__ , A__ , color='b' , alpha=0.2 , where='post' ) plt.fill_between(A__ , A__ , step='post' , alpha=0.2 , color='b' ) plt.xlabel('Recall' ) plt.ylabel('Precision' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(A__ ) plt.savefig(A__ ) plt.clf() def A_ ( A__ , A__ , A__ , A__ , A__=None , A__=None ) -> Any: a__ : str = sorted(A__ , key=lambda A__ : na_probs[k] ) a__ : Tuple = 0.0 a__ : List[str] = 1.0 a__ : Optional[int] = 0.0 a__ : Any = [1.0] a__ : Optional[int] = [0.0] a__ : Tuple = 0.0 for i, qid in enumerate(A__ ): if qid_to_has_ans[qid]: true_pos += scores[qid] a__ : Union[str, Any] = true_pos / float(i + 1 ) a__ : List[Any] = true_pos / float(A__ ) if i == len(A__ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(A__ ) recalls.append(A__ ) if out_image: plot_pr_curve(A__ , A__ , A__ , A__ ) return {"ap": 1_00.0 * avg_prec} def A_ ( A__ , A__ , A__ , A__ , A__ , A__ ) -> str: if out_image_dir and not os.path.exists(A__ ): os.makedirs(A__ ) a__ : List[str] = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return a__ : Optional[int] = make_precision_recall_eval( A__ , A__ , A__ , A__ , out_image=os.path.join(A__ , 'pr_exact.png' ) , title='Precision-Recall curve for Exact Match score' , ) a__ : Optional[int] = make_precision_recall_eval( A__ , A__ , A__ , A__ , out_image=os.path.join(A__ , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , ) a__ : int = {k: float(A__ ) for k, v in qid_to_has_ans.items()} a__ : Optional[Any] = make_precision_recall_eval( A__ , A__ , A__ , A__ , out_image=os.path.join(A__ , 'pr_oracle.png' ) , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(A__ , A__ , 'pr_exact' ) merge_eval(A__ , A__ , 'pr_f1' ) merge_eval(A__ , A__ , 'pr_oracle' ) def A_ ( A__ , A__ , A__ , A__ ) -> List[Any]: if not qid_list: return a__ : List[str] = [na_probs[k] for k in qid_list] a__ : Dict = np.ones_like(A__ ) / float(len(A__ ) ) plt.hist(A__ , weights=A__ , bins=20 , range=(0.0, 1.0) ) plt.xlabel('Model probability of no-answer' ) plt.ylabel('Proportion of dataset' ) plt.title(F'Histogram of no-answer probability: {name}' ) plt.savefig(os.path.join(A__ , F'na_prob_hist_{name}.png' ) ) plt.clf() def A_ ( A__ , A__ , A__ , A__ ) -> Optional[int]: a__ : Any = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) a__ : List[str] = num_no_ans a__ : Tuple = cur_score a__ : Tuple = 0.0 a__ : str = sorted(A__ , key=lambda A__ : na_probs[k] ) for i, qid in enumerate(A__ ): if qid not in scores: continue if qid_to_has_ans[qid]: a__ : str = scores[qid] else: if preds[qid]: a__ : int = -1 else: a__ : Tuple = 0 cur_score += diff if cur_score > best_score: a__ : Dict = cur_score a__ : Tuple = na_probs[qid] return 1_00.0 * best_score / len(A__ ), best_thresh def A_ ( A__ , A__ , A__ , A__ , A__ , A__ ) -> Optional[Any]: a__ , a__ : str = find_best_thresh(A__ , A__ , A__ , A__ ) a__ , a__ : Tuple = find_best_thresh(A__ , A__ , A__ , A__ ) a__ : Optional[Any] = best_exact a__ : Optional[Any] = exact_thresh a__ : Tuple = best_fa a__ : int = fa_thresh def A_ ( ) -> Union[str, Any]: with open(OPTS.data_file ) as f: a__ : Optional[int] = json.load(A__ ) a__ : Any = dataset_json['data'] with open(OPTS.pred_file ) as f: a__ : Optional[Any] = json.load(A__ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: a__ : int = json.load(A__ ) else: a__ : Union[str, Any] = {k: 0.0 for k in preds} a__ : str = make_qid_to_has_ans(A__ ) # maps qid to True/False a__ : int = [k for k, v in qid_to_has_ans.items() if v] a__ : Tuple = [k for k, v in qid_to_has_ans.items() if not v] a__ , a__ : str = get_raw_scores(A__ , A__ ) a__ : str = apply_no_ans_threshold(A__ , A__ , A__ , OPTS.na_prob_thresh ) a__ : Union[str, Any] = apply_no_ans_threshold(A__ , A__ , A__ , OPTS.na_prob_thresh ) a__ : List[Any] = make_eval_dict(A__ , A__ ) if has_ans_qids: a__ : str = make_eval_dict(A__ , A__ , qid_list=A__ ) merge_eval(A__ , A__ , 'HasAns' ) if no_ans_qids: a__ : int = make_eval_dict(A__ , A__ , qid_list=A__ ) merge_eval(A__ , A__ , 'NoAns' ) if OPTS.na_prob_file: find_all_best_thresh(A__ , A__ , A__ , A__ , A__ , A__ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(A__ , A__ , A__ , A__ , A__ , OPTS.out_image_dir ) histogram_na_prob(A__ , A__ , OPTS.out_image_dir , 'hasAns' ) histogram_na_prob(A__ , A__ , OPTS.out_image_dir , 'noAns' ) if OPTS.out_file: with open(OPTS.out_file , 'w' ) as f: json.dump(A__ , A__ ) else: print(json.dumps(A__ , indent=2 ) ) if __name__ == "__main__": lowercase : List[Any] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("""Agg""") import matplotlib.pyplot as plt main()
99
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : str = { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""", """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""", } class A__ ( __snake_case ): _UpperCAmelCase :Union[str, Any] = 'roberta' def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ): '''simple docstring''' super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Tuple = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Any = type_vocab_size UpperCamelCase : int = initializer_range UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = position_embedding_type UpperCamelCase : Any = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class A__ ( __snake_case ): @property def __UpperCamelCase( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
52
0
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCamelCase_ = 150_0000 ): __SCREAMING_SNAKE_CASE = defaultdict(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , UpperCamelCase_ , 2 ): if gcd(UpperCamelCase_ , UpperCamelCase_ ) > 1: continue __SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCamelCase_ , limit + 1 , UpperCamelCase_ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F"""{solution() = }""")
100
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_case ): def __init__( self , A_ , A_ ): '''simple docstring''' super().__init__() self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = 100 , A_ = None , A_ = None , A_ = True , ): '''simple docstring''' if audio_length_in_s is None: UpperCamelCase : str = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) UpperCamelCase : Union[str, Any] = int(A_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : List[str] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) UpperCamelCase : Any = int(A_ ) UpperCamelCase : Union[str, Any] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : Optional[int] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(A_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) UpperCamelCase : Optional[Any] = randn_tensor(A_ , generator=A_ , device=self.device , dtype=A_ ) # set step values self.scheduler.set_timesteps(A_ , device=audio.device ) UpperCamelCase : Optional[int] = self.scheduler.timesteps.to(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(A_ , A_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : int = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase : Optional[Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=A_ )
52
0