code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow 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 TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=13 ,A_ : Optional[Any]=30 ,A_ : List[Any]=2 ,A_ : Dict=3 ,A_ : str=True ,A_ : Any=True ,A_ : List[str]=32 ,A_ : Optional[Any]=2 ,A_ : int=4 ,A_ : Optional[Any]=37 ,A_ : Union[str, Any]="gelu" ,A_ : str=0.1 ,A_ : str=0.1 ,A_ : Tuple=10 ,A_ : Tuple=0.02 ,A_ : Optional[int]=3 ,A_ : Optional[Any]=0.6 ,A_ : Dict=None ,) -> List[str]: A = parent A = batch_size A = image_size A = patch_size A = num_channels 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 = type_sequence_label_size A = initializer_range A = mask_ratio A = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) A = (image_size // patch_size) ** 2 A = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> str: A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: return ViTMAEConfig( 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 ,decoder_hidden_size=self.hidden_size ,decoder_num_hidden_layers=self.num_hidden_layers ,decoder_num_attention_heads=self.num_attention_heads ,decoder_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=A_ ,initializer_range=self.initializer_range ,mask_ratio=self.mask_ratio ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : Union[str, Any] ) -> Tuple: A = TFViTMAEModel(config=A_ ) A = model(A_ ,training=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[str] ) -> Optional[int]: A = TFViTMAEForPreTraining(A_ ) A = model(A_ ,training=A_ ) # expected sequence length = num_patches A = (self.image_size // self.patch_size) ** 2 A = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) # test greyscale images A = 1 A = TFViTMAEForPreTraining(A_ ) A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A = model(A_ ,training=A_ ) A = self.patch_size**2 self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ((A) , (A) , (A)) = config_and_inputs A = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: int = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () _lowerCamelCase: str = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {} _lowerCamelCase: Any = False _lowerCamelCase: Any = False _lowerCamelCase: str = False _lowerCamelCase: str = False def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: A = TFViTMAEModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: 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() ,(tf.keras.layers.Layer) ) A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_ ,tf.keras.layers.Layer ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> 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_ ) A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A = [*signature.parameters.keys()] A = ['pixel_values'] self.assertListEqual(arg_names[:1] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # make the mask reproducible np.random.seed(2 ) A , A = self.model_tester.prepare_config_and_inputs_for_common() A = int((config.image_size // config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: A = model_class(A_ ) A = self._prepare_for_class(A_ ,A_ ) A = model(A_ ,noise=A_ ) A = copy.deepcopy(self._prepare_for_class(A_ ,A_ ) ) A = model(**A_ ,noise=A_ ) A = outputs_dict[0].numpy() A = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) ,1e-6 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: # make the mask reproducible np.random.seed(2 ) A , A = self.model_tester.prepare_config_and_inputs_for_common() A = int((config.image_size // config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(A_ : Union[str, Any] ): A = {} for k, v in inputs_dict.items(): if tf.is_tensor(A_ ): A = v.numpy() else: A = np.array(A_ ) return inputs_np_dict for model_class in self.all_model_classes: A = model_class(A_ ) A = self._prepare_for_class(A_ ,A_ ) A = prepare_numpy_arrays(A_ ) A = model(A_ ,noise=A_ ) A = model(**A_ ,noise=A_ ) self.assert_outputs_same(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Optional[Any] ) -> Dict: # make masks reproducible np.random.seed(2 ) A = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) A = tf.constant(A_ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument A = tf_noise super().check_pt_tf_models(A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: # make mask reproducible np.random.seed(2 ) A , A = self.model_tester.prepare_config_and_inputs_for_common() A = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(A_ ) if module_member_name.endswith('MainLayer' ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len('MainLayer' )] == model_class.__name__[: -len('Model' )] for module_member in (getattr(A_ ,A_ ),) if isinstance(A_ ,A_ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(A_ ,'_keras_serializable' ,A_ ) } A = int((config.image_size // config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) A = tf.convert_to_tensor(A_ ) inputs_dict.update({'noise': noise} ) for main_layer_class in tf_main_layer_classes: A = main_layer_class(A_ ) A = { name: tf.keras.Input(tensor.shape[1:] ,dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } A = tf.keras.Model(A_ ,outputs=main_layer(A_ ) ) A = model(A_ ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(A_ ,'keras_model.h5' ) model.save(A_ ) A = tf.keras.models.load_model( A_ ,custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(A_ ,tf.keras.Model ) A = model(A_ ) self.assert_outputs_same(A_ ,A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: # make mask reproducible np.random.seed(2 ) A , A = self.model_tester.prepare_config_and_inputs_for_common() A = int((config.image_size // config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: A = model_class(A_ ) A = self._prepare_for_class(A_ ,A_ ) A = model(A_ ,noise=A_ ) if model_class.__name__ == "TFViTMAEModel": A = outputs.last_hidden_state.numpy() A = 0 else: A = outputs.logits.numpy() A = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(A_ ,saved_model=A_ ) A = model_class.from_pretrained(A_ ) A = model(A_ ,noise=A_ ) if model_class.__name__ == "TFViTMAEModel": A = after_outputs['last_hidden_state'].numpy() A = 0 else: A = after_outputs['logits'].numpy() A = 0 A = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(A_ ,1e-5 ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: # make mask reproducible np.random.seed(2 ) A , A = self.model_tester.prepare_config_and_inputs_for_common() A = int((config.image_size // config.patch_size) ** 2 ) A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: A = model_class(A_ ) A = self._prepare_for_class(A_ ,A_ ) A = model(A_ ,noise=A_ ) A = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(A_ ) A = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config A = model_class.from_config(model.config ) A = new_model(A_ ) # Build model new_model.set_weights(model.get_weights() ) A = new_model(A_ ,noise=A_ ) self.assert_outputs_same(A_ ,A_ ) @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: pass @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = TFViTMAEModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(A_ ) def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) A = TFViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ) A = self.default_image_processor A = prepare_img() A = image_processor(images=A_ ,return_tensors='tf' ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) A = ViTMAEConfig() A = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) A = np.random.uniform(size=(1, num_patches) ) # forward pass A = model(**A_ ,noise=A_ ) # verify the logits A = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape ,A_ ) A = tf.convert_to_tensor( [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] ,A_ ,atol=1e-4 )
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() _lowercase = logging.get_logger('''transformers.models.speecht5''') _lowercase = { '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } _lowercase = { '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } _lowercase = { '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } _lowercase = { '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } _lowercase = { '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } _lowercase = { '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } _lowercase = { '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } _lowercase = { '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } _lowercase = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } _lowercase = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowercase = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowercase = [] _lowercase = [ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] _lowercase = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] _lowercase = IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] _lowercase = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def _snake_case ( snake_case__ : str , snake_case__ : Dict , snake_case__ : Dict , snake_case__ : Optional[Any] , snake_case__ : Any ): for attribute in key.split('.' ): A = getattr(snake_case__ , snake_case__ ) if weight_type is not None: A = getattr(snake_case__ , snake_case__ ).shape else: A = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": A = value elif weight_type == "weight_g": A = value elif weight_type == "weight_v": A = value elif weight_type == "bias": A = value elif weight_type == "running_mean": A = value elif weight_type == "running_var": A = value elif weight_type == "num_batches_tracked": A = value else: A = value logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def _snake_case ( snake_case__ : int , snake_case__ : str ): for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A , A = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _snake_case ( snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : Union[str, Any] ): A = [] if task == "s2t": A = hf_model.speechta.encoder.prenet.feature_encoder A = MAPPING_S2T A = IGNORE_KEYS_S2T elif task == "t2s": A = None A = MAPPING_T2S A = IGNORE_KEYS_T2S elif task == "s2s": A = hf_model.speechta.encoder.prenet.feature_encoder A = MAPPING_S2S A = IGNORE_KEYS_S2S else: raise ValueError(F'Unsupported task: {task}' ) for name, value in fairseq_dict.items(): if should_ignore(snake_case__ , snake_case__ ): logger.info(F'{name} was ignored' ) continue A = False if "conv_layers" in name: load_conv_layer( snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == 'group' , ) A = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: A , A = key.split('.*.' ) if prefix in name and suffix in name: A = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: A = True if "*" in mapped_key: A = name.split(snake_case__ )[0].split('.' )[-2] A = mapped_key.replace('*' , snake_case__ ) if "weight_g" in name: A = 'weight_g' elif "weight_v" in name: A = 'weight_v' elif "bias" in name: A = 'bias' elif "weight" in name: A = 'weight' elif "running_mean" in name: A = 'running_mean' elif "running_var" in name: A = 'running_var' elif "num_batches_tracked" in name: A = 'num_batches_tracked' else: A = None set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) continue if not is_used: unused_weights.append(snake_case__ ) logger.warning(F'Unused weights: {unused_weights}' ) def _snake_case ( snake_case__ : Optional[int] , snake_case__ : int , snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : int ): A = full_name.split('conv_layers.' )[-1] A = name.split('.' ) A = int(items[0] ) A = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) A = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) A = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) A = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) A = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(snake_case__ ) @torch.no_grad() def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : int=None , snake_case__ : Tuple=None , snake_case__ : int=None , ): if config_path is not None: A = SpeechTaConfig.from_pretrained(snake_case__ ) else: A = SpeechTaConfig() if task == "s2t": A = config.max_text_positions A = SpeechTaForSpeechToText(snake_case__ ) elif task == "t2s": A = 1876 A = 600 A = config.max_speech_positions A = SpeechTaForTextToSpeech(snake_case__ ) elif task == "s2s": A = 1876 A = config.max_speech_positions A = SpeechTaForSpeechToSpeech(snake_case__ ) else: raise ValueError(F'Unknown task name: {task}' ) if vocab_path: A = SpeechTaTokenizer(snake_case__ , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it A = AddedToken('<mask>' , lstrip=snake_case__ , rstrip=snake_case__ ) A = mask_token tokenizer.add_special_tokens({'mask_token': mask_token} ) tokenizer.add_tokens(['<ctc_blank>'] ) A = SpeechTaFeatureExtractor() A = SpeechTaProcessor(tokenizer=snake_case__ , feature_extractor=snake_case__ ) processor.save_pretrained(snake_case__ ) A = torch.load(snake_case__ ) recursively_load_weights(fairseq_checkpoint['model'] , snake_case__ , snake_case__ ) model.save_pretrained(snake_case__ ) if repo_id: print('Pushing to the hub...' ) processor.push_to_hub(snake_case__ ) model.push_to_hub(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) _lowercase = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
22
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : Optional[Any] ,A_ : Tuple=13 ,A_ : Optional[Any]=7 ,A_ : Dict=True ,A_ : Optional[Any]=True ,A_ : str=True ,A_ : Union[str, Any]=True ,A_ : Optional[Any]=True ,A_ : Tuple=False ,A_ : Optional[int]=False ,A_ : str=False ,A_ : int=2 ,A_ : Union[str, Any]=99 ,A_ : int=0 ,A_ : Dict=32 ,A_ : List[str]=5 ,A_ : Any=4 ,A_ : str=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.02 ,A_ : Optional[Any]=2 ,A_ : List[str]=4 ,A_ : Optional[int]="last" ,A_ : str=True ,A_ : List[str]=None ,A_ : List[Any]=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : List[str] ,A_ : Optional[int] ,) -> Tuple: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ,A_ : Any ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : List[str] ,A_ : List[str] ,) -> Union[str, Any]: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str ,A_ : int ,A_ : str ,A_ : Optional[Any] ,A_ : Any ,A_ : Any ,A_ : Dict ,) -> List[str]: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Dict ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : List[str] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : str ,A_ : Any ,) -> Optional[int]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : str ,) -> List[Any]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[str] ,A_ : Dict ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Dict ,A_ : Any ,) -> Any: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : str ,A_ : int ,A_ : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : int ,) -> Tuple: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: Dict = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Any ,A_ : str ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : str=False ) -> Dict: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : List[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=False ,A_ : Tuple=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Dict ,A_ : Optional[Any] ,A_ : Dict ,A_ : Tuple=False ,A_ : Optional[Any]=1 ) -> List[str]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
22
1
"""simple docstring""" 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 lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''image_processor''', '''tokenizer'''] _lowerCamelCase: Optional[int] = '''BlipImageProcessor''' _lowerCamelCase: Any = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : str ,A_ : str ,A_ : Any ) -> List[Any]: A = False super().__init__(A_ ,A_ ) A = self.image_processor def __call__( self : Dict ,A_ : ImageInput = None ,A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,A_ : bool = True ,A_ : Union[bool, str, PaddingStrategy] = False ,A_ : Union[bool, str, TruncationStrategy] = None ,A_ : Optional[int] = None ,A_ : int = 0 ,A_ : Optional[int] = None ,A_ : Optional[bool] = None ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = False ,A_ : bool = True ,A_ : Optional[Union[str, TensorType]] = None ,**A_ : Tuple ,) -> BatchEncoding: 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=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) return text_encoding # add pixel_values A = self.image_processor(A_ ,return_tensors=A_ ) if text is not None: A = self.tokenizer( text=A_ ,add_special_tokens=A_ ,padding=A_ ,truncation=A_ ,max_length=A_ ,stride=A_ ,pad_to_multiple_of=A_ ,return_attention_mask=A_ ,return_overflowing_tokens=A_ ,return_special_tokens_mask=A_ ,return_offsets_mapping=A_ ,return_token_type_ids=A_ ,return_length=A_ ,verbose=A_ ,return_tensors=A_ ,**A_ ,) else: A = None if text_encoding is not None: encoding_image_processor.update(A_ ) return encoding_image_processor def _SCREAMING_SNAKE_CASE ( self : int ,*A_ : Any ,**A_ : Optional[int] ) -> Union[str, Any]: return self.tokenizer.batch_decode(*A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,*A_ : str ,**A_ : Any ) -> Any: return self.tokenizer.decode(*A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
22
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowercase = 8 def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int]=BITS ): A = x.device A = (x * 255).int().clamp(0 , 255 ) A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b c h w -> b c 1 h w' ) A = ((x & mask) != 0).float() A = rearrange(snake_case__ , 'b c d h w -> b (c d) h w' ) A = bits * 2 - 1 return bits def _snake_case ( snake_case__ : Any , snake_case__ : Any=BITS ): A = x.device A = (x > 0).int() A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ , dtype=torch.intaa ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b (c d) h w -> b c d h w' , d=8 ) A = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def _snake_case ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : float = 0.0 , snake_case__ : bool = True , snake_case__ : List[str]=None , snake_case__ : bool = True , ): if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A = self.alphas_cumprod[timestep] A = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A = self._get_variance(snake_case__ , snake_case__ ) A = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A = model_output.device if torch.is_tensor(snake_case__ ) else 'cpu' A = torch.randn(model_output.shape , dtype=model_output.dtype , generator=snake_case__ ).to(snake_case__ ) A = self._get_variance(snake_case__ , snake_case__ ) ** 0.5 * eta * noise A = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) def _snake_case ( self : Dict , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : Tuple="epsilon" , snake_case__ : List[str]=None , snake_case__ : bool = True , ): A = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A , A = torch.split(snake_case__ , sample.shape[1] , dim=1 ) else: A = None # 1. compute alphas, betas A = self.alphas_cumprod[t] A = self.alphas_cumprod[t - 1] if t > 0 else self.one A = 1 - alpha_prod_t A = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A = 0 if t > 0: A = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=snake_case__ ).to(model_output.device ) A = (self._get_variance(snake_case__ , predicted_variance=snake_case__ ) ** 0.5) * noise A = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : UNetaDConditionModel ,A_ : Union[DDIMScheduler, DDPMScheduler] ,A_ : Optional[float] = 1.0 ,) -> Optional[int]: super().__init__() A = bit_scale A = ( ddim_bit_scheduler_step if isinstance(A_ ,A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ ,scheduler=A_ ) @torch.no_grad() def __call__( self : Tuple ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 50 ,A_ : Optional[torch.Generator] = None ,A_ : Optional[int] = 1 ,A_ : Optional[str] = "pil" ,A_ : bool = True ,**A_ : Optional[Any] ,) -> Union[Tuple, ImagePipelineOutput]: A = torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=A_ ,) A = decimal_to_bits(A_ ) * self.bit_scale A = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A = self.unet(A_ ,A_ ).sample # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,A_ ,A_ ).prev_sample A = bits_to_decimal(A_ ) if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
22
1
"""simple docstring""" from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[Any] ): A = [] for part_id in partition_order: A = df.where(F'SPARK_PARTITION_ID() = {part_id}' ).collect() for row_idx, row in enumerate(snake_case__ ): expected_row_ids_and_row_dicts.append((F'{part_id}_{row_idx}', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(100 ).repartition(1 ) A = Spark(snake_case__ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(10 ).repartition(2 ) A = [1, 0] A = _generate_iterable_examples(snake_case__ , snake_case__ ) # Reverse the partitions. A = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , snake_case__ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): A , A = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(10 ).repartition(1 ) A = SparkExamplesIterable(snake_case__ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(snake_case__ ): assert row_id == F'0_{i}' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('numpy.random.Generator' ) as generator_mock: A = lambda snake_case__ : x.reverse() A = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [2, 1, 0] ) A = SparkExamplesIterable(snake_case__ ).shuffle_data_sources(snake_case__ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(snake_case__ ): A , A = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 A = SparkExamplesIterable(snake_case__ ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 A = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [0, 2] ) for i, (row_id, row_dict) in enumerate(snake_case__ ): A , A = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 A = SparkExamplesIterable(snake_case__ ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 A = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__ , [1, 3] ) for i, (row_id, row_dict) in enumerate(snake_case__ ): A , A = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _snake_case ( ): A = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A = spark.range(100 ).repartition(1 ) A = Spark(snake_case__ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
22
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''yolos''' def __init__( self : Dict ,A_ : Optional[Any]=768 ,A_ : int=12 ,A_ : List[str]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.0 ,A_ : List[Any]=0.0 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : List[Any]=[512, 864] ,A_ : Union[str, Any]=16 ,A_ : List[str]=3 ,A_ : Optional[int]=True ,A_ : Tuple=100 ,A_ : str=True ,A_ : Optional[Any]=False ,A_ : Any=1 ,A_ : Optional[Any]=5 ,A_ : Optional[Any]=2 ,A_ : Optional[int]=5 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.1 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = num_detection_tokens A = use_mid_position_embeddings A = auxiliary_loss # Hungarian matcher A = class_cost A = bbox_cost A = giou_cost # Loss coefficients A = bbox_loss_coefficient A = giou_loss_coefficient A = eos_coefficient class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return 12
22
1
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets _lowercase = ''' @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", } ''' _lowercase = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' _lowercase = ''' 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 _snake_case ( snake_case__ : List[str] ): def remove_articles(snake_case__ : List[Any] ): A = re.compile(r'\b(a|an|the)\b' , re.UNICODE ) return re.sub(snake_case__ , ' ' , snake_case__ ) def white_space_fix(snake_case__ : Tuple ): return " ".join(text.split() ) def remove_punc(snake_case__ : int ): A = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(snake_case__ : Union[str, Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(snake_case__ ) ) ) ) def _snake_case ( snake_case__ : str , snake_case__ : List[Any] ): return int(normalize_answer(snake_case__ ) == normalize_answer(snake_case__ ) ) def _snake_case ( snake_case__ : int , snake_case__ : Union[str, Any] ): A = [any(compute_exact(snake_case__ , snake_case__ ) for ref in refs ) for pred, refs in zip(snake_case__ , snake_case__ )] return (sum(snake_case__ ) / len(snake_case__ )) * 100 def _snake_case ( snake_case__ : Tuple , snake_case__ : List[str] , snake_case__ : Tuple , snake_case__ : Optional[Any] ): A = [rgram for rgrams in rgramslist for rgram in rgrams] A = Counter(snake_case__ ) A = Counter(snake_case__ ) A = Counter() for sgram, scount in sgramcounter.items(): A = scount * numref A = Counter(snake_case__ ) A = Counter() for cgram, ccount in cgramcounter.items(): A = ccount * numref # KEEP A = sgramcounter_rep & cgramcounter_rep A = keepgramcounter_rep & rgramcounter A = sgramcounter_rep & rgramcounter A = 0 A = 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. A = 1 A = 1 if len(snake_case__ ) > 0: A = keeptmpscorea / len(snake_case__ ) if len(snake_case__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) A = keeptmpscorea / sum(keepgramcounterall_rep.values() ) A = 0 if keepscore_precision > 0 or keepscore_recall > 0: A = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION A = sgramcounter_rep - cgramcounter_rep A = delgramcounter_rep - rgramcounter A = sgramcounter_rep - rgramcounter A = 0 A = 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. A = 1 if len(snake_case__ ) > 0: A = deltmpscorea / len(snake_case__ ) # ADDITION A = set(snake_case__ ) - set(snake_case__ ) A = set(snake_case__ ) & set(snake_case__ ) A = set(snake_case__ ) - set(snake_case__ ) A = 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. A = 1 A = 1 if len(snake_case__ ) > 0: A = addtmpscore / len(snake_case__ ) if len(snake_case__ ) > 0: A = addtmpscore / len(snake_case__ ) A = 0 if addscore_precision > 0 or addscore_recall > 0: A = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : str ): A = len(snake_case__ ) A = ssent.split(' ' ) A = csent.split(' ' ) A = [] A = [] A = [] A = [] A = [] A = [] A = [] A = [] A = [] A = [] for rsent in rsents: A = rsent.split(' ' ) A = [] A = [] A = [] ragramslist.append(snake_case__ ) for i in range(0 , len(snake_case__ ) - 1 ): if i < len(snake_case__ ) - 1: A = ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(snake_case__ ) if i < len(snake_case__ ) - 2: A = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(snake_case__ ) if i < len(snake_case__ ) - 3: A = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(snake_case__ ) ragramslist.append(snake_case__ ) ragramslist.append(snake_case__ ) ragramslist.append(snake_case__ ) for i in range(0 , len(snake_case__ ) - 1 ): if i < len(snake_case__ ) - 1: A = sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(snake_case__ ) if i < len(snake_case__ ) - 2: A = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(snake_case__ ) if i < len(snake_case__ ) - 3: A = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(snake_case__ ) for i in range(0 , len(snake_case__ ) - 1 ): if i < len(snake_case__ ) - 1: A = cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(snake_case__ ) if i < len(snake_case__ ) - 2: A = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(snake_case__ ) if i < len(snake_case__ ) - 3: A = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(snake_case__ ) ((A) , (A) , (A)) = SARIngram(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) ((A) , (A) , (A)) = SARIngram(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) ((A) , (A) , (A)) = SARIngram(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) ((A) , (A) , (A)) = SARIngram(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 A = sum([delascore, delascore, delascore, delascore] ) / 4 A = sum([addascore, addascore, addascore, addascore] ) / 4 A = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def _snake_case ( snake_case__ : Dict , snake_case__ : bool = True , snake_case__ : str = "13a" , snake_case__ : bool = True ): # 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: A = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: A = sacrebleu.metrics.bleu._get_tokenizer(snake_case__ )()(snake_case__ ) else: A = sacrebleu.TOKENIZERS[tokenizer]()(snake_case__ ) elif tokenizer == "moses": A = sacremoses.MosesTokenizer().tokenize(snake_case__ , return_str=snake_case__ , escape=snake_case__ ) elif tokenizer == "penn": A = sacremoses.MosesTokenizer().penn_tokenize(snake_case__ , return_str=snake_case__ ) else: A = sentence if not return_str: A = normalized_sent.split() return normalized_sent def _snake_case ( snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : Dict ): if not (len(snake_case__ ) == len(snake_case__ ) == len(snake_case__ )): raise ValueError('Sources length must match predictions and references lengths.' ) A = 0 for src, pred, refs in zip(snake_case__ , snake_case__ , snake_case__ ): sari_score += SARIsent(normalize(snake_case__ ) , normalize(snake_case__ ) , [normalize(snake_case__ ) for sent in refs] ) A = sari_score / len(snake_case__ ) return 100 * sari_score def _snake_case ( snake_case__ : Optional[int] , snake_case__ : str , snake_case__ : Union[str, Any]="exp" , snake_case__ : Dict=None , snake_case__ : Union[str, Any]=False , snake_case__ : Dict=False , snake_case__ : Optional[Any]=False , ): A = len(references[0] ) if any(len(snake_case__ ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) A = [[refs[i] for refs in references] for i in range(snake_case__ )] A = sacrebleu.corpus_bleu( snake_case__ , snake_case__ , smooth_method=snake_case__ , smooth_value=snake_case__ , force=snake_case__ , lowercase=snake_case__ , use_effective_order=snake_case__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: 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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ,A_ : int ,A_ : Any ) -> Union[str, Any]: A = {} 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
22
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
1
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def _snake_case ( snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : int=None ): # set parameter of one layer assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match' A = nn.Parameter(snake_case__ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match' A = nn.Parameter(snake_case__ ) def _snake_case ( snake_case__ : str , snake_case__ : Optional[int] , snake_case__ : List[str] ): # set torch weights for 1-to-1 comparison A = np.asarray(weights[0] ) A = np.asarray(weights[1] ) A = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(snake_case__ ).transpose(1 , 2 ).contiguous().view(-1 , snake_case__ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case__ ).transpose(1 , 2 ).contiguous().view(-1 , snake_case__ ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case__ ).view(-1 , snake_case__ ).contiguous().transpose(0 , 1 ) , ) def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int] , snake_case__ : Dict ): # set torch weights for 1-to-1 comparison A = np.asarray(weights[0] ) A = np.asarray(weights[1] ) A = np.asarray(weights[2] ) A = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(snake_case__ ).transpose(1 , 2 ).contiguous().view(-1 , snake_case__ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(snake_case__ ).transpose(1 , 2 ).contiguous().view(-1 , snake_case__ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(snake_case__ ).transpose(1 , 2 ).contiguous().view(-1 , snake_case__ ) , ) set_param( torch_layer.output.dense , torch.tensor(snake_case__ ).view(-1 , snake_case__ ).contiguous().transpose(0 , 1 ) , ) def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : List[Any] ): # layernorm 1 A = weights[0][0][0] A = np.asarray(layer_norm_a[0] ) A = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(snake_case__ ) , torch.tensor(snake_case__ ) , ) # lsh weights + output A = weights[0][1] if len(snake_case__ ) < 4: set_layer_weights_in_torch_lsh(snake_case__ , torch_block.attention , snake_case__ ) else: set_layer_weights_in_torch_local(snake_case__ , torch_block.attention , snake_case__ ) # intermediate weighs A = weights[2][0][1][2] # Chunked Feed Forward if len(snake_case__ ) == 4: A = intermediate_weights[2] # layernorm 2 A = np.asarray(intermediate_weights[0][0] ) A = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(snake_case__ ) , torch.tensor(snake_case__ ) , ) # intermediate dense A = np.asarray(intermediate_weights[1][0] ) A = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(snake_case__ ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case__ ) , ) # intermediate out A = np.asarray(intermediate_weights[4][0] ) A = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(snake_case__ ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case__ ) , ) def _snake_case ( snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : List[Any] ): # reformer model A = torch_model.reformer # word embeds A = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(snake_case__ ) , ) if isinstance(weights[3] , snake_case__ ): A = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): A = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'{position_embeddings[emb_idx]} emb does not match' A = nn.Parameter(torch.tensor(snake_case__ ) ) A = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( snake_case__ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): A = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(snake_case__ , snake_case__ , snake_case__ ) # output layer norm A = np.asarray(weights[7][0] ) A = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(snake_case__ ) , torch.tensor(snake_case__ ) , ) # output embeddings A = np.asarray(weights[9][0] ) A = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(snake_case__ ).transpose(0 , 1 ).contiguous() , torch.tensor(snake_case__ ) , ) def _snake_case ( snake_case__ : Optional[int] , snake_case__ : List[Any] , snake_case__ : Any ): # Initialise PyTorch model A = ReformerConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = ReformerModelWithLMHead(snake_case__ ) with open(snake_case__ , 'rb' ) as f: A = pickle.load(snake_case__ )['weights'] set_model_weights_in_torch(snake_case__ , snake_case__ , config.hidden_size ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
22
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''pixel_values'''] def __init__( self : Optional[Any] ,A_ : bool = True ,A_ : Optional[Dict[str, int]] = None ,A_ : PILImageResampling = PILImageResampling.BILINEAR ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 256} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : float ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[str] ) -> np.ndarray: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Any ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : ImageInput ,A_ : Optional[bool] = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : Optional[bool] = None ,A_ : Optional[float] = None ,A_ : Optional[bool] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Union[str, ChannelDimension] = ChannelDimension.FIRST ,**A_ : Tuple ,) -> List[Any]: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : List[Tuple] = None ) -> str: A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(A_ ): A = target_sizes.numpy() A = [] for idx in range(len(A_ ) ): A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=A_ ) A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: A = logits.argmax(dim=1 ) A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
22
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''asapp/sew-d-tiny-100k''': '''https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json''', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = '''sew-d''' def __init__( self : List[str] ,A_ : Dict=32 ,A_ : Optional[int]=768 ,A_ : Optional[Any]=12 ,A_ : Optional[int]=12 ,A_ : Tuple=3072 ,A_ : Any=2 ,A_ : List[Any]=512 ,A_ : Tuple=256 ,A_ : Optional[int]=True ,A_ : List[str]=True ,A_ : List[Any]=("p2c", "c2p") ,A_ : Dict="layer_norm" ,A_ : List[str]="gelu_python" ,A_ : int=0.1 ,A_ : Tuple=0.1 ,A_ : Dict=0.1 ,A_ : List[str]=0.0 ,A_ : List[str]=0.1 ,A_ : Optional[Any]=0.02 ,A_ : Optional[int]=1e-7 ,A_ : Optional[Any]=1e-5 ,A_ : Optional[int]="group" ,A_ : Union[str, Any]="gelu" ,A_ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) ,A_ : Dict=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) ,A_ : int=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) ,A_ : Union[str, Any]=False ,A_ : str=128 ,A_ : Tuple=16 ,A_ : List[Any]=True ,A_ : Tuple=0.05 ,A_ : List[Any]=10 ,A_ : List[str]=2 ,A_ : str=0.0 ,A_ : Union[str, Any]=10 ,A_ : Tuple=0 ,A_ : Tuple="mean" ,A_ : Union[str, Any]=False ,A_ : Dict=False ,A_ : str=256 ,A_ : int=0 ,A_ : Dict=1 ,A_ : List[str]=2 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ,pad_token_id=A_ ,bos_token_id=A_ ,eos_token_id=A_ ) A = hidden_size A = feat_extract_norm A = feat_extract_activation A = list(A_ ) A = list(A_ ) A = list(A_ ) A = conv_bias A = num_conv_pos_embeddings A = num_conv_pos_embedding_groups A = len(self.conv_dim ) A = num_hidden_layers A = intermediate_size A = squeeze_factor A = max_position_embeddings A = position_buckets A = share_att_key A = relative_attention A = norm_rel_ebd A = list(A_ ) A = hidden_act A = num_attention_heads A = hidden_dropout A = attention_dropout A = activation_dropout A = feat_proj_dropout A = final_dropout A = layer_norm_eps A = feature_layer_norm_eps A = initializer_range A = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A = apply_spec_augment A = mask_time_prob A = mask_time_length A = mask_time_min_masks A = mask_feature_prob A = mask_feature_length A = mask_feature_min_masks # ctc loss A = ctc_loss_reduction A = ctc_zero_infinity # sequence classification A = use_weighted_layer_sum A = classifier_proj_size @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: return functools.reduce(operator.mul ,self.conv_stride ,1 )
22
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
1
"""simple docstring""" import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Optional[int]=None ,A_ : List[Any]=None ,A_ : int=None ,A_ : Optional[int]="resnet50" ,A_ : Optional[Any]=3 ,A_ : Any=32 ,A_ : Any=3 ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,) -> Dict: A = parent A = out_indices if out_indices is not None else [4] A = stage_names A = out_features A = backbone A = batch_size A = image_size A = num_channels A = use_pretrained_backbone A = is_training def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A = self.get_config() return config, pixel_values def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return TimmBackboneConfig( image_size=self.image_size ,num_channels=self.num_channels ,out_features=self.out_features ,out_indices=self.out_indices ,stage_names=self.stage_names ,use_pretrained_backbone=self.use_pretrained_backbone ,backbone=self.backbone ,) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[str] ,A_ : int ) -> List[str]: A = TimmBackbone(config=A_ ) model.to(A_ ) model.eval() with torch.no_grad(): A = model(A_ ) self.parent.assertEqual( result.feature_map[-1].shape ,(self.batch_size, model.channels[-1], 14, 14) ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = self.prepare_config_and_inputs() A , A = config_and_inputs A = {'pixel_values': pixel_values} return config, inputs_dict @require_torch @require_timm class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = (TimmBackbone,) if is_torch_available() else () _lowerCamelCase: Union[str, Any] = {'''feature-extraction''': TimmBackbone} if is_torch_available() else {} _lowerCamelCase: Union[str, Any] = False _lowerCamelCase: str = False _lowerCamelCase: Tuple = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: A = TimmBackboneModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'resnet18' A = 'microsoft/resnet-18' A = AutoBackbone.from_pretrained(A_ ,use_timm_backbone=A_ ) A = AutoBackbone.from_pretrained(A_ ) self.assertEqual(len(timm_model.out_features ) ,len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) ,len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels ,transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices ,(-1,) ) self.assertEqual(transformers_model.out_indices ,[len(timm_model.stage_names ) - 1] ) A = AutoBackbone.from_pretrained(A_ ,use_timm_backbone=A_ ,out_indices=[1, 2, 3] ) A = AutoBackbone.from_pretrained(A_ ,out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices ,transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) ,len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels ,transformers_model.channels ) @unittest.skip('TimmBackbone doesn\'t support feed forward chunking' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: pass @unittest.skip('TimmBackbone initialization is managed on the timm side' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: pass @unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: pass @unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: pass @unittest.skip('TimmBackbone doesn\'t support output_attentions.' ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: pass @unittest.skip('Safetensors is not supported by timm.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: pass def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A , A = self.model_tester.prepare_config_and_inputs_for_common() A = True A = self.has_attentions # no need to test all models as different heads yield the same functionality A = self.all_model_classes[0] A = model_class(A_ ) model.to(A_ ) A = self._prepare_for_class(A_ ,A_ ) A = model(**A_ ) A = outputs[0][-1] # Encoder-/Decoder-only models A = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: A = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=A_ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) model.to(A_ ) model.eval() A = model(**A_ ) self.assertEqual(len(result.feature_maps ) ,len(config.out_indices ) ) self.assertEqual(len(model.channels ) ,len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None A = copy.deepcopy(A_ ) A = None A = model_class(A_ ) model.to(A_ ) model.eval() A = model(**A_ ) self.assertEqual(len(result.feature_maps ) ,1 ) self.assertEqual(len(model.channels ) ,1 ) # Check backbone can be initialized with fresh weights A = copy.deepcopy(A_ ) A = False A = model_class(A_ ) model.to(A_ ) model.eval() A = model(**A_ )
22
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ) -> int: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Optional[Any]=1 ) -> int: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Dict ) -> Optional[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int=-2 ,A_ : Dict=-1 ) -> str: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Any=-1 ) -> int: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Union[str, Any]=-2 ) -> Optional[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ) -> Any: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ) -> str: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any]=-2 ) -> Any: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple=-2 ,A_ : List[str]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any]=-2 ) -> Dict: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[str]=1 ) -> Dict: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : List[str] ) -> List[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=-2 ,A_ : List[Any]=-1 ) -> int: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int]=-1 ) -> List[Any]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict=-2 ) -> List[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ) -> List[Any]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any]=-2 ,A_ : List[str]=-1 ) -> Any: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any]=-2 ) -> Union[str, Any]: A = time() self.bfs(A_ ) A = time() return end - begin
22
1
"""simple docstring""" _lowercase = [0, 2, 4, 6, 8] _lowercase = [1, 3, 5, 7, 9] def _snake_case ( snake_case__ : int , snake_case__ : int , snake_case__ : list[int] , snake_case__ : int ): if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 A = 0 for digit in range(10 ): A = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , snake_case__ , snake_case__ ) return result A = 0 for digita in range(10 ): A = digita if (remainder + digita) % 2 == 0: A = ODD_DIGITS else: A = EVEN_DIGITS for digita in other_parity_digits: A = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , snake_case__ , snake_case__ , ) return result def _snake_case ( snake_case__ : int = 9 ): A = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(snake_case__ , 0 , [0] * length , snake_case__ ) return result if __name__ == "__main__": print(F"""{solution() = }""")
22
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
1
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : dict , snake_case__ : str ): A , A = set(snake_case__ ), [start] while stack: A = stack.pop() explored.add(snake_case__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(snake_case__ ) return explored _lowercase = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''PerceiverFeatureExtractor'''] _lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : int ,A_ : int=12 ,A_ : Union[str, Any]=7 ,A_ : List[Any]=True ,A_ : str=True ,A_ : Optional[Any]=True ,A_ : str=99 ,A_ : Any=32 ,A_ : Tuple=32 ,A_ : List[str]=2 ,A_ : Dict=4 ,A_ : int=37 ,A_ : Optional[int]=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : str=0.02 ,A_ : int=0 ,A_ : str=None ,) -> List[str]: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_labels A = vocab_size A = hidden_size A = projection_dim A = num_hidden_layers A = num_attention_heads A = intermediate_size A = dropout A = attention_dropout A = max_position_embeddings A = initializer_range A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: A = input_mask.numpy() A , A = input_mask.shape A = np.random.randint(1 ,seq_length - 1 ,size=(batch_size,) ) for batch_idx, start_index in enumerate(A_ ): A = 1 A = 0 A = self.get_config() return config, input_ids, tf.convert_to_tensor(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: return BlipTextConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,projection_dim=self.projection_dim ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,dropout=self.dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ,A_ : Optional[int] ,A_ : Optional[int] ) -> Dict: A = TFBlipTextModel(config=A_ ) A = model(A_ ,attention_mask=A_ ,training=A_ ) A = model(A_ ,training=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 _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = self.prepare_config_and_inputs() A , A , A = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = (TFBlipTextModel,) if is_tf_available() else () _lowerCamelCase: Any = False _lowerCamelCase: Any = False _lowerCamelCase: List[str] = False def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: A = BlipTextModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: pass @unittest.skip(reason='Blip does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: pass @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: pass @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> str: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = TFBlipTextModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any]=True ) -> List[str]: super().test_pt_tf_model_equivalence(allow_missing_keys=A_ )
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
1
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
"""simple docstring""" from math import pi, sqrt def _snake_case ( snake_case__ : float ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(snake_case__ ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(snake_case__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _snake_case ( ): assert gamma(0.5 ) == sqrt(snake_case__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input('''Gamma of: ''')) print(F"""gamma({num}) = {gamma(num)}""") print('''\nEnter 0 to exit...''')
22
1
"""simple docstring""" from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def _snake_case ( ): import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join A = '__test_patch_submodule_mock__' with patch_submodule(_test_patching , 'os.path.join' , snake_case__ ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def _snake_case ( ): assert _test_patching.open is open A = '__test_patch_submodule_builtin_mock__' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , 'open' , snake_case__ ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def _snake_case ( ): # pandas.read_csv is not present in _test_patching A = '__test_patch_submodule_missing_mock__' with patch_submodule(_test_patching , 'pandas.read_csv' , snake_case__ ): pass def _snake_case ( ): # builtin should always be mocked even if they're not in the globals # in case they're loaded at one point A = '__test_patch_submodule_missing_builtin_mock__' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , 'len' , snake_case__ ) is None with patch_submodule(_test_patching , 'len' , snake_case__ ): assert _test_patching.len is mock assert _test_patching.len is len def _snake_case ( ): A = '__test_patch_submodule_start_and_stop_mock__' A = patch_submodule(_test_patching , 'open' , snake_case__ ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def _snake_case ( ): from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join A = '__test_patch_submodule_successive_join__' A = '__test_patch_submodule_successive_dirname__' A = '__test_patch_submodule_successive_rename__' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , 'os.path.join' , snake_case__ ): with patch_submodule(_test_patching , 'os.rename' , snake_case__ ): with patch_submodule(_test_patching , 'os.path.dirname' , snake_case__ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , 'os.rename' , snake_case__ ): with patch_submodule(_test_patching , 'os.path.join' , snake_case__ ): with patch_submodule(_test_patching , 'os.path.dirname' , snake_case__ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def _snake_case ( ): A = '__test_patch_submodule_doesnt_exist_mock__' with patch_submodule(_test_patching , '__module_that_doesn_exist__.__attribute_that_doesn_exist__' , snake_case__ ): pass with patch_submodule(_test_patching , 'os.__attribute_that_doesn_exist__' , snake_case__ ): pass
22
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,A_ : Dict=3 ,A_ : int=3 ,A_ : str=("DownEncoderBlock2D",) ,A_ : Dict=(64,) ,A_ : str=2 ,A_ : Union[str, Any]=32 ,A_ : Optional[int]="silu" ,A_ : str=True ,) -> Union[str, Any]: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Dict ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any]=3 ,A_ : Optional[int]=3 ,A_ : str=("UpDecoderBlock2D",) ,A_ : Any=(64,) ,A_ : Optional[int]=2 ,A_ : Optional[int]=32 ,A_ : Tuple="silu" ,A_ : Optional[int]="group" ,) -> Any: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Union[str, Any]=None ) -> Any: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : List[Any] ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict=None ,A_ : List[Any]="random" ,A_ : Optional[int]=False ,A_ : str=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ) -> Any: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ) -> str: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : str ) -> Union[str, Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Tuple ,A_ : Dict=False ) -> List[str]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple=None ) -> int: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[str] ,A_ : Union[str, Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return self.mean
22
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _lowercase = logging.get_logger(__name__) if is_vision_available(): import PIL class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''pixel_values'''] def __init__( self : Union[str, Any] ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : bool = True ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 224} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,default_to_square=A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A = image_std if image_std is not None else OPENAI_CLIP_STD A = do_convert_rgb def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Union[str, Any] ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : str ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : np.ndarray ,A_ : Union[int, float] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Union[str, Any] ,) -> Union[str, Any]: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[Any] ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : ImageInput ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : int = None ,A_ : bool = None ,A_ : float = None ,A_ : bool = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : bool = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Optional[ChannelDimension] = ChannelDimension.FIRST ,**A_ : Dict ,) -> PIL.Image.Image: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,param_name='size' ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ,default_to_square=A_ ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: A = [convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ )
22
"""simple docstring""" def _snake_case ( snake_case__ : list , snake_case__ : list , snake_case__ : int ): A = len(snake_case__ ) A = [[0] * n for i in range(snake_case__ )] for i in range(snake_case__ ): A = y_points[i] for i in range(2 , snake_case__ ): for j in range(snake_case__ , snake_case__ ): A = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
22
1
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter _lowercase = True except ImportError: _lowercase = False _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( snake_case__ : Namespace ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' ,action='store_true' ,help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' ,type=A_ ,help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' ,type=A_ ,help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=A_ ) def __init__( self : Tuple ,A_ : bool ,A_ : str ,A_ : Tuple=None ,*A_ : List[str] ) -> Union[str, Any]: A = testing A = testing_file A = path def _SCREAMING_SNAKE_CASE ( self : int ) -> int: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory A = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(A_ ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) A = ( Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) A = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(A_ ) ) else: with open(self._testing_file ,'r' ) as configuration_file: A = json.load(A_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) ,no_input=A_ ,extra_context=A_ ,) A = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' ,'r' ) as configuration_file: A = json.load(A_ ) A = configuration['lowercase_modelname'] A = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F'{directory}/configuration.json' ) A = 'PyTorch' in generate_tensorflow_pytorch_and_flax A = 'TensorFlow' in generate_tensorflow_pytorch_and_flax A = 'Flax' in generate_tensorflow_pytorch_and_flax A = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(A_ ,exist_ok=A_ ) os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' ,exist_ok=A_ ) # Tests require submodules as they have parent imports with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' ,'w' ): pass shutil.move( F'{directory}/__init__.py' ,F'{model_dir}/__init__.py' ,) shutil.move( F'{directory}/configuration_{lowercase_model_name}.py' ,F'{model_dir}/configuration_{lowercase_model_name}.py' ,) def remove_copy_lines(A_ : int ): with open(A_ ,'r' ) as f: A = f.readlines() with open(A_ ,'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(A_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_{lowercase_model_name}.py' ,F'{model_dir}/modeling_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_tf_{lowercase_model_name}.py' ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_flax_{lowercase_model_name}.py' ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/{lowercase_model_name}.md' ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' ,) shutil.move( F'{directory}/tokenization_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/tokenization_fast_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' ,) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(A_ : str ,A_ : str ,A_ : List[str] ): # Create temp file A , A = mkstemp() A = False with fdopen(A_ ,'w' ) as new_file: with open(A_ ) as old_file: for line in old_file: new_file.write(A_ ) if line_to_copy_below in line: A = True for line_to_copy in lines_to_copy: new_file.write(A_ ) if not line_found: raise ValueError(F'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(A_ ,A_ ) # Remove original file remove(A_ ) # Move new file move(A_ ,A_ ) def skip_units(A_ : Dict ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(A_ : Tuple ): with open(A_ ) as datafile: A = [] A = False A = False for line in datafile: if "# To replace in: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# Below: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(A_ ,A_ ,A_ ) A = [] elif "# Replace with" in line and "##" not in line: A = [] elif "##" not in line: lines_to_copy.append(A_ ) remove(A_ ) replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(A_ )
22
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[Any] ,A_ : Optional[int]=2 ,A_ : Any=True ,A_ : List[str]=False ,A_ : Tuple=10 ,A_ : List[Any]=3 ,A_ : Any=32 * 8 ,A_ : Dict=32 * 8 ,A_ : List[Any]=4 ,A_ : Tuple=64 ,) -> List[str]: A = parent A = batch_size A = is_training A = use_auxiliary_loss A = num_queries A = num_channels A = min_size A = max_size A = num_labels A = hidden_dim A = hidden_dim def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A_ ) A = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=A_ ) A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=A_ ) > 0.5 ).float() A = (torch.rand((self.batch_size, self.num_labels) ,device=A_ ) > 0.5).long() A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A = self.num_queries A = self.num_labels A = [1, 1, 1, 1] A = self.num_channels A = 64 A = 128 A = self.hidden_dim A = self.hidden_dim A = self.hidden_dim return config def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A , A , A , A , A = self.prepare_config_and_inputs() A = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = output.encoder_hidden_states A = output.pixel_decoder_hidden_states A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : List[str] ,A_ : Union[str, Any]=False ) -> str: with torch.no_grad(): A = MaskaFormerModel(config=A_ ) model.to(A_ ) model.eval() A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ,output_hidden_states=A_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : Any ,A_ : Dict ,A_ : Any ,A_ : Dict ) -> Optional[Any]: A = MaskaFormerForUniversalSegmentation(config=A_ ) model.to(A_ ) model.eval() def comm_check_on_output(A_ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ) comm_check_on_output(A_ ) A = model( pixel_values=A_ ,pixel_mask=A_ ,mask_labels=A_ ,class_labels=A_ ) comm_check_on_output(A_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCamelCase: Optional[Any] = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} _lowerCamelCase: int = False _lowerCamelCase: Dict = False _lowerCamelCase: List[str] = False _lowerCamelCase: int = False def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = MaskaFormerModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) A = inspect.signature(model.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_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A = MaskaFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = (self.model_tester.min_size,) * 2 A = { 'pixel_values': torch.randn((2, 3, *size) ,device=A_ ), 'mask_labels': torch.randn((2, 10, *size) ,device=A_ ), 'class_labels': torch.zeros(2 ,10 ,device=A_ ).long(), } A = self.model_tester.get_config() A = MaskaFormerForUniversalSegmentation(A_ ).to(A_ ) A = model(**A_ ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ).to(A_ ) A = model(**A_ ,output_attentions=A_ ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: if not self.model_tester.is_training: return A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = model_class(A_ ) model.to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = True A = True A = model_class(A_ ).to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ) A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowercase = 1e-4 def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A_ ) A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) A = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) # masks_queries_logits A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] A = torch.tensor(A_ ).to(A_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,A_ ,atol=A_ ) ) # class_queries_logits A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(A_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) A = inputs['pixel_values'].to(A_ ) A = [el.to(A_ ) for el in inputs['mask_labels']] A = [el.to(A_ ) for el in inputs['class_labels']] with torch.no_grad(): A = model(**A_ ) self.assertTrue(outputs.loss is not None )
22
1
"""simple docstring""" def _snake_case ( snake_case__ : str , snake_case__ : list[str] ): A = '' for word_or_phrase in separated: if not isinstance(snake_case__ , snake_case__ ): raise Exception('join() accepts only strings to be joined' ) joined += word_or_phrase + separator return joined.strip(snake_case__ ) if __name__ == "__main__": from doctest import testmod testmod()
22
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any] ,) -> Optional[int]: A = parent A = 13 A = 7 A = True A = True A = True A = 99 A = 32 A = 2 A = 4 A = 37 A = 'gelu' A = 0.1 A = 0.1 A = 512 A = 16 A = 2 A = 0.02 A = 3 A = 4 A = None def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = EsmConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,pad_token_id=1 ,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 ,) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[Any] ,A_ : Any ,A_ : Any ) -> Dict: A = TFEsmModel(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,) -> Optional[int]: A = True A = TFEsmModel(config=A_ ) A = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ,encoder_hidden_states=A_ ) # Also check the case where encoder outputs are not passed A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ) -> Dict: A = TFEsmForMaskedLM(config=A_ ) A = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Optional[int] ) -> Union[str, Any]: A = self.num_labels A = TFEsmForTokenClassification(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _lowerCamelCase: List[str] = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) _lowerCamelCase: Union[str, Any] = False _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: A = TFEsmModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = TFEsmModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: pass @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer A = model.get_bias() assert isinstance(A_ ,A_ ) for k, v in name.items(): assert isinstance(A_ ,tf.Variable ) else: A = model.get_output_embeddings() assert x is None A = model.get_bias() assert name is None @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 1, 2, 3, 4, 5]] ) A = model(A_ )[0] A = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) ,A_ ) # compare the actual values for a slice. A = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-2 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) A = model(A_ )[0] # compare the actual values for a slice. A = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
22
1
"""simple docstring""" import numpy as np from PIL import Image def _snake_case ( snake_case__ : np.ndarray , snake_case__ : int , snake_case__ : int ): A = np.array(snake_case__ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) A = 0 A = 0 A = 0 A = 0 # compute the shape of the output matrix A = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape A = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix A = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 A = 0 A = 0 return updated_arr def _snake_case ( snake_case__ : np.ndarray , snake_case__ : int , snake_case__ : int ): A = np.array(snake_case__ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) A = 0 A = 0 A = 0 A = 0 # compute the shape of the output matrix A = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape A = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix A = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 A = 0 A = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image _lowercase = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
22
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys _lowercase = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') _lowercase = subprocess.check_output(F"""git diff --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() _lowercase = '''|'''.join(sys.argv[1:]) _lowercase = re.compile(rF"""^({joined_dirs}).*?\.py$""") _lowercase = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
22
1
"""simple docstring""" import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = GPTaTokenizer _lowerCamelCase: int = GPTaTokenizerFast _lowerCamelCase: Dict = True _lowerCamelCase: Optional[int] = {'''add_prefix_space''': True} _lowerCamelCase: Tuple = False def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] A = {'unk_token': '<unk>'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,**A_ : int ) -> Dict: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,**A_ : Any ) -> Optional[int]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : int ) -> int: A = 'lower newer' A = 'lower newer' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = GPTaTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) A = 'lower newer' A = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] A = tokenizer.tokenize(A_ ,add_prefix_space=A_ ) self.assertListEqual(A_ ,A_ ) A = tokens + [tokenizer.unk_token] A = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: if not self.test_rust_tokenizer: return A = self.get_tokenizer() A = self.get_rust_tokenizer(add_prefix_space=A_ ) A = 'lower newer' # Testing tokenization A = tokenizer.tokenize(A_ ,add_prefix_space=A_ ) A = rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) # Testing conversion to ids without special tokens A = tokenizer.encode(A_ ,add_special_tokens=A_ ,add_prefix_space=A_ ) A = rust_tokenizer.encode(A_ ,add_special_tokens=A_ ) self.assertListEqual(A_ ,A_ ) # Testing conversion to ids with special tokens A = self.get_rust_tokenizer(add_prefix_space=A_ ) A = tokenizer.encode(A_ ,add_prefix_space=A_ ) A = rust_tokenizer.encode(A_ ) self.assertListEqual(A_ ,A_ ) # Testing the unknown token A = tokens + [rust_tokenizer.unk_token] A = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ,*A_ : List[Any] ,**A_ : Optional[int] ) -> Any: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int]=15 ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A = self.rust_tokenizer_class.from_pretrained(A_ ,**A_ ) # Simple input A = 'This is a simple input' A = ['This is a simple input 1', 'This is a simple input 2'] A = ('This is a simple input', 'This is a pair') A = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ ,tokenizer_r.encode ,A_ ,max_length=A_ ,padding='max_length' ) # Simple input self.assertRaises(A_ ,tokenizer_r.encode_plus ,A_ ,max_length=A_ ,padding='max_length' ) # Simple input self.assertRaises( A_ ,tokenizer_r.batch_encode_plus ,A_ ,max_length=A_ ,padding='max_length' ,) # Pair input self.assertRaises(A_ ,tokenizer_r.encode ,A_ ,max_length=A_ ,padding='max_length' ) # Pair input self.assertRaises(A_ ,tokenizer_r.encode_plus ,A_ ,max_length=A_ ,padding='max_length' ) # Pair input self.assertRaises( A_ ,tokenizer_r.batch_encode_plus ,A_ ,max_length=A_ ,padding='max_length' ,) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = GPTaTokenizer.from_pretrained(self.tmpdirname ,pad_token='<pad>' ) # Simple input A = 'This is a simple input' A = ['This is a simple input looooooooong', 'This is a simple input'] A = ('This is a simple input', 'This is a pair') A = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] A = tokenizer.pad_token_id A = tokenizer(A_ ,padding='max_length' ,max_length=30 ,return_tensors='np' ) A = tokenizer(A_ ,padding=A_ ,truncate=A_ ,return_tensors='np' ) A = tokenizer(*A_ ,padding='max_length' ,max_length=60 ,return_tensors='np' ) A = tokenizer(A_ ,padding=A_ ,truncate=A_ ,return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] ,30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] ,33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] ,60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] ,52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: A = '$$$' A = GPTaTokenizer.from_pretrained(self.tmpdirname ,bos_token=A_ ,add_bos_token=A_ ) A = 'This is a simple input' A = ['This is a simple input 1', 'This is a simple input 2'] A = tokenizer.bos_token_id A = tokenizer(A_ ) A = tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] ,A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) A = tokenizer.decode(out_s.input_ids ) A = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] ,A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: pass def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented A = [self.get_tokenizer(do_lower_case=A_ ,add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A = 'Encode this.' A = 'This one too please.' A = tokenizer.encode(A_ ,add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ ,add_special_tokens=A_ ) A = tokenizer.encode_plus( A_ ,A_ ,add_special_tokens=A_ ,return_special_tokens_mask=A_ ,) A = encoded_sequence_dict['input_ids'] A = encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) ,len(A_ ) ) A = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] A = [x for x in filtered_sequence if x is not None] self.assertEqual(A_ ,A_ ) @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 A = AutoTokenizer.from_pretrained('facebook/opt-350m' ,from_slow=A_ ) A = 'A photo of a cat' A = tokenizer.encode( A_ ,) self.assertEqual(A_ ,[2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) A = AutoTokenizer.from_pretrained('./test_opt' ) A = tokenizer.encode( A_ ,) self.assertEqual(A_ ,[2, 250, 1345, 9, 10, 4758] ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = AutoTokenizer.from_pretrained('facebook/opt-350m' ,use_slow=A_ ) A = 'A photo of a cat' A = tokenizer.encode( A_ ,) # Same as above self.assertEqual(A_ ,[2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = AutoTokenizer.from_pretrained('facebook/opt-350m' ,from_slow=A_ ) A = 'bos' A = tokenizer.get_vocab()['bos'] A = 'A photo of a cat' A = tokenizer.encode( A_ ,) # We changed the bos token self.assertEqual(A_ ,[3_1957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) A = AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) A = tokenizer.encode( A_ ,) self.assertEqual(A_ ,[3_1957, 250, 1345, 9, 10, 4758] )
22
"""simple docstring""" import sys from collections import defaultdict class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ) -> int: A = [] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> Optional[int]: return self.node_position[vertex] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ,A_ : Any ) -> List[Any]: A = pos def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : str ,A_ : Dict ,A_ : List[str] ) -> str: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: A = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: A = 2 * start + 1 else: A = 2 * start + 2 if heap[smallest_child] < heap[start]: A , A = heap[smallest_child], positions[smallest_child] A , A = ( heap[start], positions[start], ) A , A = temp, tempa A = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] ,self.get_position(positions[start] ) ) self.set_position(positions[start] ,A_ ) self.top_to_bottom(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : Dict ,A_ : str ,A_ : Union[str, Any] ) -> Dict: A = position[index] while index != 0: A = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: A = heap[parent] A = position[parent] self.set_position(position[parent] ,A_ ) else: A = val A = temp self.set_position(A_ ,A_ ) break A = parent else: A = val A = temp self.set_position(A_ ,0 ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple ,A_ : Dict ) -> Union[str, Any]: A = len(A_ ) // 2 - 1 for i in range(A_ ,-1 ,-1 ): self.top_to_bottom(A_ ,A_ ,len(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ,A_ : Dict ) -> Union[str, Any]: A = positions[0] A = sys.maxsize self.top_to_bottom(A_ ,0 ,len(A_ ) ,A_ ) return temp def _snake_case ( snake_case__ : Dict ): A = Heap() A = [0] * len(snake_case__ ) A = [-1] * len(snake_case__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph A = [] # Heap of Distance of vertices from their neighboring vertex A = [] for vertex in range(len(snake_case__ ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case__ ) heap.node_position.append(snake_case__ ) A = [] A = 1 A = sys.maxsize for neighbor, distance in adjacency_list[0]: A = 0 A = distance heap.heapify(snake_case__ , snake_case__ ) for _ in range(1 , len(snake_case__ ) ): A = heap.delete_minimum(snake_case__ , snake_case__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) A = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case__ )] ): A = distance heap.bottom_to_top( snake_case__ , heap.get_position(snake_case__ ) , snake_case__ , snake_case__ ) A = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > _lowercase = int(input('''Enter number of edges: ''').strip()) _lowercase = defaultdict(list) for _ in range(edges_number): _lowercase = [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))
22
1
"""simple docstring""" def _snake_case ( snake_case__ : int ): A = abs(snake_case__ ) A = 0 while n > 0: res += n % 10 n //= 10 return res def _snake_case ( snake_case__ : int ): A = abs(snake_case__ ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def _snake_case ( snake_case__ : int ): return sum(int(snake_case__ ) for c in str(abs(snake_case__ ) ) ) def _snake_case ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(snake_case__ : Callable , snake_case__ : int ) -> None: A = F'{func.__name__}({value})' A = timeit(F'__main__.{call}' , setup='import __main__' ) print(F'{call:56} = {func(snake_case__ )} -- {timing:.4f} seconds' ) for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(snake_case__ , snake_case__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
22
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter _lowercase = True except ImportError: _lowercase = False _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( snake_case__ : Namespace ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' ,action='store_true' ,help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' ,type=A_ ,help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' ,type=A_ ,help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=A_ ) def __init__( self : Tuple ,A_ : bool ,A_ : str ,A_ : Tuple=None ,*A_ : List[str] ) -> Union[str, Any]: A = testing A = testing_file A = path def _SCREAMING_SNAKE_CASE ( self : int ) -> int: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory A = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(A_ ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) A = ( Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) A = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(A_ ) ) else: with open(self._testing_file ,'r' ) as configuration_file: A = json.load(A_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) ,no_input=A_ ,extra_context=A_ ,) A = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' ,'r' ) as configuration_file: A = json.load(A_ ) A = configuration['lowercase_modelname'] A = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F'{directory}/configuration.json' ) A = 'PyTorch' in generate_tensorflow_pytorch_and_flax A = 'TensorFlow' in generate_tensorflow_pytorch_and_flax A = 'Flax' in generate_tensorflow_pytorch_and_flax A = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(A_ ,exist_ok=A_ ) os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' ,exist_ok=A_ ) # Tests require submodules as they have parent imports with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' ,'w' ): pass shutil.move( F'{directory}/__init__.py' ,F'{model_dir}/__init__.py' ,) shutil.move( F'{directory}/configuration_{lowercase_model_name}.py' ,F'{model_dir}/configuration_{lowercase_model_name}.py' ,) def remove_copy_lines(A_ : int ): with open(A_ ,'r' ) as f: A = f.readlines() with open(A_ ,'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(A_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_{lowercase_model_name}.py' ,F'{model_dir}/modeling_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_tf_{lowercase_model_name}.py' ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_flax_{lowercase_model_name}.py' ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/{lowercase_model_name}.md' ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' ,) shutil.move( F'{directory}/tokenization_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/tokenization_fast_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' ,) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(A_ : str ,A_ : str ,A_ : List[str] ): # Create temp file A , A = mkstemp() A = False with fdopen(A_ ,'w' ) as new_file: with open(A_ ) as old_file: for line in old_file: new_file.write(A_ ) if line_to_copy_below in line: A = True for line_to_copy in lines_to_copy: new_file.write(A_ ) if not line_found: raise ValueError(F'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(A_ ,A_ ) # Remove original file remove(A_ ) # Move new file move(A_ ,A_ ) def skip_units(A_ : Dict ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(A_ : Tuple ): with open(A_ ) as datafile: A = [] A = False A = False for line in datafile: if "# To replace in: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# Below: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(A_ ,A_ ,A_ ) A = [] elif "# Replace with" in line and "##" not in line: A = [] elif "##" not in line: lines_to_copy.append(A_ ) remove(A_ ) replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(A_ )
22
1
"""simple docstring""" def _snake_case ( snake_case__ : Tuple , snake_case__ : List[Any] ): A = 0 A = len(snake_case__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(snake_case__ ): return None A = sorted_collection[point] if current_item == item: return point else: if point < left: A = left A = point elif point > right: A = right A = point else: if item < current_item: A = point - 1 else: A = point + 1 return None def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : int , snake_case__ : Union[str, Any] , snake_case__ : List[Any] ): # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(snake_case__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) elif point > right: return interpolation_search_by_recursion(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( snake_case__ , snake_case__ , snake_case__ , point - 1 ) else: return interpolation_search_by_recursion( snake_case__ , snake_case__ , point + 1 , snake_case__ ) def _snake_case ( snake_case__ : Dict ): if collection != sorted(snake_case__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys _lowercase = 0 if debug == 1: _lowercase = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit('''Sequence must be ascending sorted to apply interpolation search''') _lowercase = 67 _lowercase = interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print('''Not found''')
22
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : int ,A_ : Tuple ,A_ : str=7 ,A_ : Tuple=3 ,A_ : List[Any]=18 ,A_ : List[str]=30 ,A_ : Optional[Any]=400 ,A_ : Any=True ,A_ : Optional[Any]=None ,A_ : List[str]=True ,) -> str: A = size if size is not None else {'height': 18, 'width': 18} A = parent A = batch_size A = num_channels A = image_size A = min_resolution A = max_resolution A = do_resize A = size A = do_normalize def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04], [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ImageGPTImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ ,'clusters' ) ) self.assertTrue(hasattr(A_ ,'do_resize' ) ) self.assertTrue(hasattr(A_ ,'size' ) ) self.assertTrue(hasattr(A_ ,'do_normalize' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'height': 18, 'width': 18} ) A = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'height': 42, 'width': 42} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: A = self.image_processing_class(**self.image_processor_dict ) A = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,obj[key] ) ) else: self.assertEqual(obj[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(A_ ,'image_processor.json' ) image_processor_first.to_json_file(A_ ) A = self.image_processing_class.from_json_file(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(A_ ) A = self.image_processing_class.from_pretrained(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) @unittest.skip('ImageGPT requires clusters at initialization' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: pass def _snake_case ( ): A = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) A = Image.open(dataset[4]['file'] ) A = Image.open(dataset[5]['file'] ) A = [imagea, imagea] return images @require_vision @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) A = prepare_images() # test non-batched A = image_processing(images[0] ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(1, 1024) ) A = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() ,A_ ) # test batched A = image_processing(A_ ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(2, 1024) ) A = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() ,A_ )
22
1
"""simple docstring""" import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) _lowercase = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _snake_case ( snake_case__ : str , snake_case__ : str ): A = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1024, 'hidden_size': 768, 'max_length': 512, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 1024, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } A = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py A = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=snake_case__ , output_all_encodings=snake_case__ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , snake_case__ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later A = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab A = os.path.join(get_home_dir() , 'models' ) A = _load_vocab(snake_case__ , snake_case__ , snake_case__ , cls=snake_case__ ) A = nlp.model.BERTModel( snake_case__ , len(snake_case__ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=snake_case__ , use_token_type_embed=snake_case__ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=snake_case__ , use_decoder=snake_case__ , ) original_bort.load_parameters(snake_case__ , cast_dtype=snake_case__ , ignore_extra=snake_case__ ) A = original_bort._collect_params_with_prefix() # Build our config 🤗 A = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(snake_case__ ), } A = BertConfig.from_dict(snake_case__ ) A = BertForMaskedLM(snake_case__ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(snake_case__ : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(snake_case__ : Tuple , snake_case__ : Union[str, Any] ): A = hf_param.shape A = to_torch(params[gluon_param] ) A = gluon_param.shape assert ( shape_hf == shape_gluon ), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param A = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) A = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) A = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) A = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) A = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): A = hf_bort_model.bert.encoder.layer[i] # self attention A = layer.attention.self A = check_and_map_params( self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) A = check_and_map_params( self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) A = check_and_map_params( self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) A = check_and_map_params( self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) A = check_and_map_params( self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) A = check_and_map_params( self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output A = layer.attention.output A = check_and_map_params( self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' ) A = check_and_map_params( self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' ) A = check_and_map_params( self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' ) A = check_and_map_params( self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate A = layer.intermediate A = check_and_map_params( intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) A = check_and_map_params( intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output A = layer.output A = check_and_map_params( bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) A = check_and_map_params( bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) A = check_and_map_params( bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) A = check_and_map_params( bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models A = RobertaTokenizer.from_pretrained('roberta-base' ) A = tokenizer.encode_plus(snake_case__ )['input_ids'] # Get gluon output A = mx.nd.array([input_ids] ) A = original_bort(inputs=snake_case__ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(snake_case__ ) A = BertModel.from_pretrained(snake_case__ ) hf_bort_model.eval() A = tokenizer.encode_plus(snake_case__ , return_tensors='pt' ) A = hf_bort_model(**snake_case__ )[0] A = output_gluon[0].asnumpy() A = output_hf[0].detach().numpy() A = np.max(np.abs(hf_layer - gluon_layer ) ).item() A = np.allclose(snake_case__ , snake_case__ , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
22
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def _snake_case ( snake_case__ : Optional[int] ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' ,type=A_ ,default=A_ ,help='Path to location to store the models' ) download_parser.add_argument( '--force' ,action='store_true' ,help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' ,action='store_true' ,help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' ,) download_parser.add_argument('model' ,type=A_ ,help='Name of the model to download' ) download_parser.set_defaults(func=A_ ) def __init__( self : Dict ,A_ : str ,A_ : str ,A_ : bool ,A_ : bool ) -> Union[str, Any]: A = model A = cache A = force A = trust_remote_code def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code )
22
1
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowercase = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = '''mask2former''' _lowerCamelCase: Dict = ['''swin'''] _lowerCamelCase: Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any ,A_ : Optional[Dict] = None ,A_ : int = 256 ,A_ : int = 256 ,A_ : int = 256 ,A_ : int = 1024 ,A_ : str = "relu" ,A_ : int = 6 ,A_ : int = 10 ,A_ : int = 8 ,A_ : float = 0.0 ,A_ : int = 2048 ,A_ : bool = False ,A_ : bool = False ,A_ : int = 4 ,A_ : int = 255 ,A_ : int = 100 ,A_ : float = 0.1 ,A_ : float = 2.0 ,A_ : float = 5.0 ,A_ : float = 5.0 ,A_ : int = 1_2544 ,A_ : float = 3.0 ,A_ : float = 0.75 ,A_ : float = 0.02 ,A_ : float = 1.0 ,A_ : bool = True ,A_ : List[int] = [4, 8, 16, 32] ,A_ : bool = None ,**A_ : Optional[int] ,) -> Optional[int]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) A = CONFIG_MAPPING['swin']( image_size=224 ,in_channels=3 ,patch_size=4 ,embed_dim=96 ,depths=[2, 2, 18, 2] ,num_heads=[3, 6, 12, 24] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=A_ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(A_ ,A_ ): A = backbone_config.pop('model_type' ) A = CONFIG_MAPPING[backbone_model_type] A = config_class.from_dict(A_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ' F'Supported model types: {",".join(self.backbones_supported )}' ) A = backbone_config A = feature_size A = mask_feature_size A = hidden_dim A = encoder_feedforward_dim A = activation_function A = encoder_layers A = decoder_layers A = num_attention_heads A = dropout A = dim_feedforward A = pre_norm A = enforce_input_projection A = common_stride A = ignore_value A = num_queries A = no_object_weight A = class_weight A = mask_weight A = dice_weight A = train_num_points A = oversample_ratio A = importance_sample_ratio A = init_std A = init_xavier_std A = use_auxiliary_loss A = feature_strides A = output_auxiliary_logits A = decoder_layers super().__init__(**A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,A_ : PretrainedConfig ,**A_ : Dict ) -> Union[str, Any]: return cls( backbone_config=A_ ,**A_ ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict[str, any]: A = copy.deepcopy(self.__dict__ ) A = self.backbone_config.to_dict() A = self.__class__.model_type return output
22
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''spm_char.model'''} _lowercase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowercase = { '''microsoft/speecht5_asr''': 10_24, '''microsoft/speecht5_tts''': 10_24, '''microsoft/speecht5_vc''': 10_24, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None: A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Any: A = self.__dict__.copy() A = None return state def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]: return self.sp_model.piece_to_id(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]: A = self.sp_model.IdToPiece(A_ ) return token def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: A = [] A = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) A = [1] if token_ids_a is None: return ([0] * len(A_ )) + suffix_ones return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
22
1
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class lowerCAmelCase_ : '''simple docstring''' def __init__( self : str ,A_ : Union[str, Any] ,A_ : Optional[Any]=14 ,A_ : Any=7 ,A_ : Union[str, Any]=True ,A_ : Optional[int]=True ,A_ : Optional[Any]=False ,A_ : int=True ,A_ : Any=99 ,A_ : Dict=32 ,A_ : str=4 ,A_ : Any=4 ,A_ : Optional[Any]=4 ,A_ : List[Any]=37 ,A_ : Optional[int]="gelu" ,A_ : Dict=0.1 ,A_ : Optional[int]=0.1 ,A_ : Any=512 ,A_ : int=0.02 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = rotary_dim A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = initializer_range A = None A = vocab_size - 1 A = vocab_size - 1 A = vocab_size - 1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = GPTJConfig( vocab_size=self.vocab_size ,n_embd=self.hidden_size ,n_layer=self.num_hidden_layers ,n_head=self.num_attention_heads ,n_positions=self.max_position_embeddings ,use_cache=A_ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,rotary_dim=self.rotary_dim ,) return (config, input_ids, input_mask) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = self.prepare_config_and_inputs() A , A , A = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Any ,A_ : List[str] ,A_ : List[str] ,A_ : Tuple ) -> int: A = 20 A = model_class_name(A_ ) A = model.init_cache(input_ids.shape[0] ,A_ ) A = jnp.ones((input_ids.shape[0], max_decoder_length) ,dtype='i4' ) A = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] ,(input_ids.shape[0], input_ids.shape[-1] - 1) ) A = model( input_ids[:, :-1] ,attention_mask=A_ ,past_key_values=A_ ,position_ids=A_ ,) A = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] ,dtype='i4' ) A = model( input_ids[:, -1:] ,attention_mask=A_ ,past_key_values=outputs_cache.past_key_values ,position_ids=A_ ,) A = model(A_ ) A = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 ,msg=F'Max diff is {diff}' ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ) -> Optional[Any]: A = 20 A = model_class_name(A_ ) A = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] ,axis=-1 ,) A = model.init_cache(input_ids.shape[0] ,A_ ) A = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] ,(input_ids.shape[0], input_ids.shape[-1] - 1) ) A = model( input_ids[:, :-1] ,attention_mask=A_ ,past_key_values=A_ ,position_ids=A_ ,) A = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] ,dtype='i4' ) A = model( input_ids[:, -1:] ,past_key_values=outputs_cache.past_key_values ,attention_mask=A_ ,position_ids=A_ ,) A = model(A_ ,attention_mask=A_ ) A = 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_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () _lowerCamelCase: Optional[Any] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: A = FlaxGPTJModelTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: for model_class_name in self.all_model_classes: A , A , A = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: for model_class_name in self.all_model_classes: A , A , A = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( A_ ,A_ ,A_ ,A_ ) @tooslow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: A = GPTaTokenizer.from_pretrained('gpt2' ,pad_token='<|endoftext|>' ,padding_side='left' ) A = tokenizer(['Hello this is a long string', 'Hey'] ,return_tensors='np' ,padding=A_ ,truncation=A_ ) A = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) A = False A = model.config.eos_token_id A = jax.jit(model.generate ) A = jit_generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,pad_token_id=tokenizer.pad_token_id ).sequences A = tokenizer.batch_decode(A_ ,skip_special_tokens=A_ ) A = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(A_ ,A_ ) @is_pt_flax_cross_test def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs A = self._prepare_for_class(A_ ,A_ ) A = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class A = model_class.__name__[4:] # Skip the "Flax" at the beginning A = getattr(A_ ,A_ ) A , A = pt_inputs['input_ids'].shape A = np.random.randint(0 ,seq_length - 1 ,size=(batch_size,) ) for batch_idx, start_index in enumerate(A_ ): A = 0 A = 1 A = 0 A = 1 A = pt_model_class(A_ ).eval() A = model_class(A_ ,dtype=jnp.floataa ) A = convert_pytorch_state_dict_to_flax(pt_model.state_dict() ,A_ ) A = fx_state with torch.no_grad(): A = pt_model(**A_ ).to_tuple() A = fx_model(**A_ ).to_tuple() self.assertEqual(len(A_ ) ,len(A_ ) ,'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(A_ ,A_ ): self.assert_almost_equals(fx_output[:, -1] ,pt_output[:, -1].numpy() ,4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(A_ ) A = model_class.from_pretrained(A_ ,from_pt=A_ ) A = fx_model_loaded(**A_ ).to_tuple() self.assertEqual( len(A_ ) ,len(A_ ) ,'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(A_ ,A_ ): self.assert_almost_equals(fx_output_loaded[:, -1] ,pt_output[:, -1].numpy() ,4e-2 ) @is_pt_flax_cross_test def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs A = self._prepare_for_class(A_ ,A_ ) A = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class A = model_class.__name__[4:] # Skip the "Flax" at the beginning A = getattr(A_ ,A_ ) A = pt_model_class(A_ ).eval() A = model_class(A_ ,dtype=jnp.floataa ) A = load_flax_weights_in_pytorch_model(A_ ,fx_model.params ) A , A = pt_inputs['input_ids'].shape A = np.random.randint(0 ,seq_length - 1 ,size=(batch_size,) ) for batch_idx, start_index in enumerate(A_ ): A = 0 A = 1 A = 0 A = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): A = pt_model(**A_ ).to_tuple() A = fx_model(**A_ ).to_tuple() self.assertEqual(len(A_ ) ,len(A_ ) ,'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(A_ ,A_ ): self.assert_almost_equals(fx_output[:, -1] ,pt_output[:, -1].numpy() ,4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(A_ ) A = pt_model_class.from_pretrained(A_ ,from_flax=A_ ) with torch.no_grad(): A = pt_model_loaded(**A_ ).to_tuple() self.assertEqual( len(A_ ) ,len(A_ ) ,'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(A_ ,A_ ): self.assert_almost_equals(fx_output[:, -1] ,pt_output[:, -1].numpy() ,4e-2 ) @tooslow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: for model_class_name in self.all_model_classes: A = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) A = model(np.ones((1, 1) ) ) self.assertIsNotNone(A_ )
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig if is_timm_available(): import timm if is_torch_available(): from torch import Tensor class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: str = '''pixel_values''' _lowerCamelCase: Any = False _lowerCamelCase: List[Any] = TimmBackboneConfig def __init__( self : str ,A_ : Tuple ,**A_ : Union[str, Any] ) -> Any: requires_backends(self ,'timm' ) super().__init__(A_ ) A = config if config.backbone is None: raise ValueError('backbone is not set in the config. Please set it to a timm model name.' ) if config.backbone not in timm.list_models(): raise ValueError(F'backbone {config.backbone} is not supported by timm.' ) if hasattr(A_ ,'out_features' ) and config.out_features is not None: raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.' ) A = getattr(A_ ,'use_pretrained_backbone' ,A_ ) if pretrained is None: raise ValueError('use_pretrained_backbone is not set in the config. Please set it to True or False.' ) # We just take the final layer by default. This matches the default for the transformers models. A = config.out_indices if getattr(A_ ,'out_indices' ,A_ ) is not None else (-1,) A = timm.create_model( config.backbone ,pretrained=A_ ,features_only=config.features_only ,in_chans=config.num_channels ,out_indices=A_ ,**A_ ,) # These are used to control the output of the model when called. If output_hidden_states is True, then # return_layers is modified to include all layers. A = self._backbone.return_layers A = {layer['module']: str(A_ ) for i, layer in enumerate(self._backbone.feature_info.info )} super()._init_backbone(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,A_ : Union[str, Any] ,*A_ : List[Any] ,**A_ : Optional[Any] ) -> Optional[Any]: requires_backends(cls ,['vision', 'timm'] ) from ...models.timm_backbone import TimmBackboneConfig A = kwargs.pop('config' ,TimmBackboneConfig() ) A = kwargs.pop('use_timm_backbone' ,A_ ) if not use_timm: raise ValueError('use_timm_backbone must be True for timm backbones' ) A = kwargs.pop('num_channels' ,config.num_channels ) A = kwargs.pop('features_only' ,config.features_only ) A = kwargs.pop('use_pretrained_backbone' ,config.use_pretrained_backbone ) A = kwargs.pop('out_indices' ,config.out_indices ) A = TimmBackboneConfig( backbone=A_ ,num_channels=A_ ,features_only=A_ ,use_pretrained_backbone=A_ ,out_indices=A_ ,) return super()._from_config(A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Any ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : int ,A_ : int ,A_ : Optional[int]=None ,A_ : Any=None ,A_ : List[Any]=None ,**A_ : Optional[int] ) -> Union[BackboneOutput, Tuple[Tensor, ...]]: A = return_dict if return_dict is not None else self.config.use_return_dict A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A = output_attentions if output_attentions is not None else self.config.output_attentions if output_attentions: raise ValueError('Cannot output attentions for timm backbones at the moment' ) if output_hidden_states: # We modify the return layers to include all the stages of the backbone A = self._all_layers A = self._backbone(A_ ,**A_ ) A = self._return_layers A = tuple(hidden_states[i] for i in self.out_indices ) else: A = self._backbone(A_ ,**A_ ) A = None A = tuple(A_ ) A = tuple(A_ ) if hidden_states is not None else None if not return_dict: A = (feature_maps,) if output_hidden_states: A = output + (hidden_states,) return output return BackboneOutput(feature_maps=A_ ,hidden_states=A_ ,attentions=A_ )
22
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : Optional[Any] ,A_ : Tuple=13 ,A_ : Optional[Any]=7 ,A_ : Dict=True ,A_ : Optional[Any]=True ,A_ : str=True ,A_ : Union[str, Any]=True ,A_ : Optional[Any]=True ,A_ : Tuple=False ,A_ : Optional[int]=False ,A_ : str=False ,A_ : int=2 ,A_ : Union[str, Any]=99 ,A_ : int=0 ,A_ : Dict=32 ,A_ : List[str]=5 ,A_ : Any=4 ,A_ : str=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.02 ,A_ : Optional[Any]=2 ,A_ : List[str]=4 ,A_ : Optional[int]="last" ,A_ : str=True ,A_ : List[str]=None ,A_ : List[Any]=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : List[str] ,A_ : Optional[int] ,) -> Tuple: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ,A_ : Any ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : List[str] ,A_ : List[str] ,) -> Union[str, Any]: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str ,A_ : int ,A_ : str ,A_ : Optional[Any] ,A_ : Any ,A_ : Any ,A_ : Dict ,) -> List[str]: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Dict ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : List[str] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : str ,A_ : Any ,) -> Optional[int]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : str ,) -> List[Any]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[str] ,A_ : Dict ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Dict ,A_ : Any ,) -> Any: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : str ,A_ : int ,A_ : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : int ,) -> Tuple: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: Dict = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Any ,A_ : str ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : str=False ) -> Dict: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : List[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=False ,A_ : Tuple=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Dict ,A_ : Optional[Any] ,A_ : Dict ,A_ : Tuple=False ,A_ : Optional[Any]=1 ) -> List[str]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
22
1
"""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 KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
22
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowercase = 8 def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int]=BITS ): A = x.device A = (x * 255).int().clamp(0 , 255 ) A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b c h w -> b c 1 h w' ) A = ((x & mask) != 0).float() A = rearrange(snake_case__ , 'b c d h w -> b (c d) h w' ) A = bits * 2 - 1 return bits def _snake_case ( snake_case__ : Any , snake_case__ : Any=BITS ): A = x.device A = (x > 0).int() A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ , dtype=torch.intaa ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b (c d) h w -> b c d h w' , d=8 ) A = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def _snake_case ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : float = 0.0 , snake_case__ : bool = True , snake_case__ : List[str]=None , snake_case__ : bool = True , ): if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A = self.alphas_cumprod[timestep] A = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A = self._get_variance(snake_case__ , snake_case__ ) A = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A = model_output.device if torch.is_tensor(snake_case__ ) else 'cpu' A = torch.randn(model_output.shape , dtype=model_output.dtype , generator=snake_case__ ).to(snake_case__ ) A = self._get_variance(snake_case__ , snake_case__ ) ** 0.5 * eta * noise A = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) def _snake_case ( self : Dict , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : Tuple="epsilon" , snake_case__ : List[str]=None , snake_case__ : bool = True , ): A = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A , A = torch.split(snake_case__ , sample.shape[1] , dim=1 ) else: A = None # 1. compute alphas, betas A = self.alphas_cumprod[t] A = self.alphas_cumprod[t - 1] if t > 0 else self.one A = 1 - alpha_prod_t A = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A = 0 if t > 0: A = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=snake_case__ ).to(model_output.device ) A = (self._get_variance(snake_case__ , predicted_variance=snake_case__ ) ** 0.5) * noise A = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : UNetaDConditionModel ,A_ : Union[DDIMScheduler, DDPMScheduler] ,A_ : Optional[float] = 1.0 ,) -> Optional[int]: super().__init__() A = bit_scale A = ( ddim_bit_scheduler_step if isinstance(A_ ,A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ ,scheduler=A_ ) @torch.no_grad() def __call__( self : Tuple ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 50 ,A_ : Optional[torch.Generator] = None ,A_ : Optional[int] = 1 ,A_ : Optional[str] = "pil" ,A_ : bool = True ,**A_ : Optional[Any] ,) -> Union[Tuple, ImagePipelineOutput]: A = torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=A_ ,) A = decimal_to_bits(A_ ) * self.bit_scale A = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A = self.unet(A_ ,A_ ).sample # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,A_ ,A_ ).prev_sample A = bits_to_decimal(A_ ) if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
22
1
"""simple docstring""" def _snake_case ( snake_case__ : int ): A = int(snake_case__ ) if n_element < 1: A = ValueError('a should be a positive number' ) raise my_error A = [1] A , A , A = (0, 0, 0) A = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _lowercase = input('''Enter the last number (nth term) of the Hamming Number Series: ''') print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''') _lowercase = hamming(int(n)) print('''-----------------------------------------------------''') print(F"""The list with nth numbers is: {hamming_numbers}""") print('''-----------------------------------------------------''')
22
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''yolos''' def __init__( self : Dict ,A_ : Optional[Any]=768 ,A_ : int=12 ,A_ : List[str]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.0 ,A_ : List[Any]=0.0 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : List[Any]=[512, 864] ,A_ : Union[str, Any]=16 ,A_ : List[str]=3 ,A_ : Optional[int]=True ,A_ : Tuple=100 ,A_ : str=True ,A_ : Optional[Any]=False ,A_ : Any=1 ,A_ : Optional[Any]=5 ,A_ : Optional[Any]=2 ,A_ : Optional[int]=5 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.1 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = num_detection_tokens A = use_mid_position_embeddings A = auxiliary_loss # Hungarian matcher A = class_cost A = bbox_cost A = giou_cost # Loss coefficients A = bbox_loss_coefficient A = giou_loss_coefficient A = eos_coefficient class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return 12
22
1
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[Any] ,A_ : Optional[int]=2 ,A_ : Any=True ,A_ : List[str]=False ,A_ : Tuple=10 ,A_ : List[Any]=3 ,A_ : Any=32 * 8 ,A_ : Dict=32 * 8 ,A_ : List[Any]=4 ,A_ : Tuple=64 ,) -> List[str]: A = parent A = batch_size A = is_training A = use_auxiliary_loss A = num_queries A = num_channels A = min_size A = max_size A = num_labels A = hidden_dim A = hidden_dim def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A_ ) A = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=A_ ) A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=A_ ) > 0.5 ).float() A = (torch.rand((self.batch_size, self.num_labels) ,device=A_ ) > 0.5).long() A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A = self.num_queries A = self.num_labels A = [1, 1, 1, 1] A = self.num_channels A = 64 A = 128 A = self.hidden_dim A = self.hidden_dim A = self.hidden_dim return config def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A , A , A , A , A = self.prepare_config_and_inputs() A = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = output.encoder_hidden_states A = output.pixel_decoder_hidden_states A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : List[str] ,A_ : Union[str, Any]=False ) -> str: with torch.no_grad(): A = MaskaFormerModel(config=A_ ) model.to(A_ ) model.eval() A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ,output_hidden_states=A_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : Any ,A_ : Dict ,A_ : Any ,A_ : Dict ) -> Optional[Any]: A = MaskaFormerForUniversalSegmentation(config=A_ ) model.to(A_ ) model.eval() def comm_check_on_output(A_ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ) comm_check_on_output(A_ ) A = model( pixel_values=A_ ,pixel_mask=A_ ,mask_labels=A_ ,class_labels=A_ ) comm_check_on_output(A_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCamelCase: Optional[Any] = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} _lowerCamelCase: int = False _lowerCamelCase: Dict = False _lowerCamelCase: List[str] = False _lowerCamelCase: int = False def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = MaskaFormerModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) A = inspect.signature(model.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_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A = MaskaFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = (self.model_tester.min_size,) * 2 A = { 'pixel_values': torch.randn((2, 3, *size) ,device=A_ ), 'mask_labels': torch.randn((2, 10, *size) ,device=A_ ), 'class_labels': torch.zeros(2 ,10 ,device=A_ ).long(), } A = self.model_tester.get_config() A = MaskaFormerForUniversalSegmentation(A_ ).to(A_ ) A = model(**A_ ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ).to(A_ ) A = model(**A_ ,output_attentions=A_ ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: if not self.model_tester.is_training: return A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = model_class(A_ ) model.to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = True A = True A = model_class(A_ ).to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ) A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowercase = 1e-4 def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A_ ) A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) A = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) # masks_queries_logits A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] A = torch.tensor(A_ ).to(A_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,A_ ,atol=A_ ) ) # class_queries_logits A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(A_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) A = inputs['pixel_values'].to(A_ ) A = [el.to(A_ ) for el in inputs['mask_labels']] A = [el.to(A_ ) for el in inputs['class_labels']] with torch.no_grad(): A = model(**A_ ) self.assertTrue(outputs.loss is not None )
22
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
1
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''pixel_values'''] def __init__( self : Optional[Any] ,A_ : bool = True ,A_ : Optional[Dict[str, int]] = None ,A_ : PILImageResampling = PILImageResampling.BILINEAR ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 256} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : float ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[str] ) -> np.ndarray: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Any ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : ImageInput ,A_ : Optional[bool] = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : Optional[bool] = None ,A_ : Optional[float] = None ,A_ : Optional[bool] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Union[str, ChannelDimension] = ChannelDimension.FIRST ,**A_ : Tuple ,) -> List[Any]: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : List[Tuple] = None ) -> str: A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(A_ ): A = target_sizes.numpy() A = [] for idx in range(len(A_ ) ): A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=A_ ) A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: A = logits.argmax(dim=1 ) A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
22
1
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''char''' _lowerCamelCase: List[Any] = '''bpe''' _lowerCamelCase: Optional[Any] = '''wp''' _lowercase = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''image_processor''', '''char_tokenizer'''] _lowerCamelCase: Optional[int] = '''ViTImageProcessor''' _lowerCamelCase: Union[str, Any] = '''MgpstrTokenizer''' def __init__( self : List[Any] ,A_ : Dict=None ,A_ : List[str]=None ,**A_ : Union[str, Any] ) -> Tuple: A = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,A_ ,) A = kwargs.pop('feature_extractor' ) A = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) A = tokenizer A = AutoTokenizer.from_pretrained('gpt2' ) A = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(A_ ,A_ ) def __call__( self : Dict ,A_ : str=None ,A_ : Tuple=None ,A_ : str=None ,**A_ : Dict ) -> Dict: if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: A = self.image_processor(A_ ,return_tensors=A_ ,**A_ ) if text is not None: A = self.char_tokenizer(A_ ,return_tensors=A_ ,**A_ ) if text is None: return inputs elif images is None: return encodings else: A = encodings['input_ids'] return inputs def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Dict ) -> List[str]: A , A , A = sequences A = char_preds.size(0 ) A , A = self._decode_helper(A_ ,'char' ) A , A = self._decode_helper(A_ ,'bpe' ) A , A = self._decode_helper(A_ ,'wp' ) A = [] A = [] for i in range(A_ ): A = [char_scores[i], bpe_scores[i], wp_scores[i]] A = [char_strs[i], bpe_strs[i], wp_strs[i]] A = scores.index(max(A_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) A = {} A = final_strs A = final_scores A = char_strs A = bpe_strs A = wp_strs return out def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : str ,A_ : int ) -> int: if format == DecodeType.CHARACTER: A = self.char_decode A = 1 A = '[s]' elif format == DecodeType.BPE: A = self.bpe_decode A = 2 A = '#' elif format == DecodeType.WORDPIECE: A = self.wp_decode A = 102 A = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) A , A = [], [] A = pred_logits.size(0 ) A = pred_logits.size(1 ) A , A = pred_logits.topk(1 ,dim=-1 ,largest=A_ ,sorted=A_ ) A = preds_index.view(-1 ,A_ )[:, 1:] A = decoder(A_ ) A , A = torch.nn.functional.softmax(A_ ,dim=2 ).max(dim=2 ) A = preds_max_prob[:, 1:] for index in range(A_ ): A = preds_str[index].find(A_ ) A = preds_str[index][:pred_eos] A = preds_index[index].cpu().tolist() A = pred_index.index(A_ ) if eos_token in pred_index else -1 A = preds_max_prob[index][: pred_eos_index + 1] A = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(A_ ) conf_scores.append(A_ ) return dec_strs, conf_scores def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : str ) -> Optional[Any]: A = [seq.replace(' ' ,'' ) for seq in self.char_tokenizer.batch_decode(A_ )] return decode_strs def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : int ) -> List[Any]: return self.bpe_tokenizer.batch_decode(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> str: A = [seq.replace(' ' ,'' ) for seq in self.wp_tokenizer.batch_decode(A_ )] return decode_strs
22
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
1
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = 1 A = 3 A = (32, 32) A = floats_tensor((batch_size, num_channels) + sizes ,rng=random.Random(0 ) ).to(A_ ) return image @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=32 ,) return model @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) return model @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: torch.manual_seed(0 ) A = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) return CLIPTextModel(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: def extract(*A_ : List[str] ,**A_ : int ): class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ) -> Optional[Any]: A = torch.ones([0] ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Union[str, Any] ) -> int: self.pixel_values.to(A_ ) return self return Out() return extract def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.dummy_cond_unet A = DDIMScheduler( beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule='scaled_linear' ,clip_sample=A_ ,set_alpha_to_one=A_ ,) A = self.dummy_vae A = self.dummy_text_encoder A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) # make sure here that pndm scheduler skips prk A = StableDiffusionPipeline( unet=A_ ,scheduler=A_ ,vae=A_ ,text_encoder=A_ ,tokenizer=A_ ,safety_checker=A_ ,feature_extractor=self.dummy_extractor ,) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = 'A painting of a squirrel eating a burger' A = torch.Generator(device=A_ ).manual_seed(0 ) A = sd_pipe([prompt] ,generator=A_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ) A = output.images A = torch.Generator(device=A_ ).manual_seed(0 ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ,return_dict=A_ ,)[0] A = image[0, -3:, -3:, -1] A = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A = np.array([0.57_56, 0.61_18, 0.50_05, 0.50_41, 0.54_71, 0.47_26, 0.49_76, 0.48_65, 0.48_64] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: A = 'cpu' # ensure determinism for the device-dependent torch.Generator A = self.dummy_cond_unet A = PNDMScheduler(skip_prk_steps=A_ ) A = self.dummy_vae A = self.dummy_text_encoder A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) # make sure here that pndm scheduler skips prk A = StableDiffusionPipeline( unet=A_ ,scheduler=A_ ,vae=A_ ,text_encoder=A_ ,tokenizer=A_ ,safety_checker=A_ ,feature_extractor=self.dummy_extractor ,) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = 'A painting of a squirrel eating a burger' A = torch.Generator(device=A_ ).manual_seed(0 ) A = sd_pipe([prompt] ,generator=A_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ) A = output.images A = torch.Generator(device=A_ ).manual_seed(0 ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ,return_dict=A_ ,)[0] A = image[0, -3:, -3:, -1] A = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A = np.array([0.51_25, 0.57_16, 0.48_28, 0.50_60, 0.56_50, 0.47_68, 0.51_85, 0.48_95, 0.49_93] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = StableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-lms-pipe' ,safety_checker=A_ ) assert isinstance(A_ ,A_ ) assert isinstance(pipe.scheduler ,A_ ) assert pipe.safety_checker is None A = pipe('example prompt' ,num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(A_ ) A = StableDiffusionPipeline.from_pretrained(A_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None A = pipe('example prompt' ,num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != 'cuda' ,'This test requires a GPU' ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: A = self.dummy_cond_unet A = PNDMScheduler(skip_prk_steps=A_ ) A = self.dummy_vae A = self.dummy_text_encoder A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) # put models in fp16 A = unet.half() A = vae.half() A = bert.half() # make sure here that pndm scheduler skips prk A = StableDiffusionPipeline( unet=A_ ,scheduler=A_ ,vae=A_ ,text_encoder=A_ ,tokenizer=A_ ,safety_checker=A_ ,feature_extractor=self.dummy_extractor ,) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = 'A painting of a squirrel eating a burger' A = sd_pipe([prompt] ,num_inference_steps=2 ,output_type='np' ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: A = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' ,safety_checker=A_ ) A = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = ( 'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle' ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with' ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and' ' children from bahnhof zoo, detailed ' ) A = 40_0366_0346 A = 7 # without safety guidance (sld_guidance_scale = 0) A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,) A = output.images A = image[0, -3:, -3:, -1] A = [0.22_78, 0.22_31, 0.22_49, 0.23_33, 0.23_03, 0.18_85, 0.22_73, 0.21_44, 0.21_76] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,) A = output.images A = image[0, -3:, -3:, -1] A = [0.23_83, 0.22_76, 0.2_36, 0.21_92, 0.21_86, 0.20_53, 0.19_71, 0.19_01, 0.17_19] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' ,safety_checker=A_ ) A = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = 'padme amidala taking a bath artwork, safe for work, no nudity' A = 27_3497_1755 A = 7 A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,) A = output.images A = image[0, -3:, -3:, -1] A = [0.35_02, 0.36_22, 0.33_96, 0.36_42, 0.34_78, 0.33_18, 0.35, 0.33_48, 0.32_97] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,) A = output.images A = image[0, -3:, -3:, -1] A = [0.55_31, 0.52_06, 0.48_95, 0.51_56, 0.51_82, 0.47_51, 0.48_02, 0.48_03, 0.44_43] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' ) A = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) A = ( 'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.' ' leyendecker' ) A = 10_4435_5234 A = 12 A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,) A = output.images A = image[0, -3:, -3:, -1] A = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 A = torch.manual_seed(A_ ) A = sd_pipe( [prompt] ,generator=A_ ,guidance_scale=A_ ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,) A = output.images A = image[0, -3:, -3:, -1] A = np.array([0.58_18, 0.62_85, 0.68_35, 0.60_19, 0.6_25, 0.67_54, 0.60_96, 0.63_34, 0.65_61] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
22
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ) -> int: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Optional[Any]=1 ) -> int: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Dict ) -> Optional[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int=-2 ,A_ : Dict=-1 ) -> str: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Any=-1 ) -> int: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Union[str, Any]=-2 ) -> Optional[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ) -> Any: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ) -> str: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any]=-2 ) -> Any: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple=-2 ,A_ : List[str]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any]=-2 ) -> Dict: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[str]=1 ) -> Dict: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : List[str] ) -> List[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=-2 ,A_ : List[Any]=-1 ) -> int: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int]=-1 ) -> List[Any]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict=-2 ) -> List[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ) -> List[Any]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any]=-2 ,A_ : List[str]=-1 ) -> Any: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any]=-2 ) -> Union[str, Any]: A = time() self.bfs(A_ ) A = time() return end - begin
22
1
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Optional[int] ,A_ : Tuple=99 ,A_ : Any=13 ,A_ : List[str]=7 ,A_ : Any=9 ,A_ : Optional[int]=True ,A_ : Tuple=True ,A_ : List[Any]=False ,A_ : List[str]=32 ,A_ : List[Any]=5 ,A_ : Tuple=4 ,A_ : Optional[int]=37 ,A_ : List[str]=8 ,A_ : List[Any]=0.1 ,A_ : List[Any]=0.0_02 ,A_ : List[Any]=1 ,A_ : int=0 ,A_ : Optional[int]=0 ,A_ : Tuple=None ,A_ : Any=None ,) -> Union[str, Any]: A = parent A = batch_size A = encoder_seq_length A = decoder_seq_length # For common tests A = self.decoder_seq_length A = is_training A = use_attention_mask A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = d_ff A = relative_attention_num_buckets A = dropout_rate A = initializer_factor A = eos_token_id A = pad_token_id A = decoder_start_token_id A = None A = decoder_layers def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: return TaConfig.from_pretrained('google/umt5-base' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Any=None ,A_ : Dict=None ,A_ : List[Any]=None ,A_ : int=None ,A_ : List[str]=None ,) -> Optional[Any]: if attention_mask is None: A = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: A = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: A = torch.ones(config.num_hidden_layers ,config.num_attention_heads ,device=A_ ) if decoder_head_mask is None: A = torch.ones(config.num_decoder_layers ,config.num_attention_heads ,device=A_ ) if cross_attn_head_mask is None: A = torch.ones( config.num_decoder_layers ,config.num_attention_heads ,device=A_ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = ids_tensor([self.batch_size, self.encoder_seq_length] ,self.vocab_size ) A = ids_tensor([self.batch_size, self.decoder_seq_length] ,self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input A = input_ids.clamp(self.pad_token_id + 1 ) A = decoder_input_ids.clamp(self.pad_token_id + 1 ) A = self.get_config() A = config.num_attention_heads A = self.prepare_inputs_dict(A_ ,A_ ,A_ ) return config, input_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A , A = self.prepare_config_and_inputs() return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: return TaConfig( vocab_size=166 ,d_model=self.hidden_size ,d_ff=self.d_ff ,d_kv=self.hidden_size // self.num_attention_heads ,num_layers=self.num_hidden_layers ,num_decoder_layers=self.decoder_layers ,num_heads=self.num_attention_heads ,relative_attention_num_buckets=self.relative_attention_num_buckets ,dropout_rate=self.dropout_rate ,initializer_factor=self.initializer_factor ,eos_token_id=self.eos_token_id ,bos_token_id=self.pad_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.decoder_start_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: return TaConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,d_ff=self.d_ff ,d_kv=self.hidden_size // self.num_attention_heads ,num_layers=self.num_hidden_layers ,num_decoder_layers=self.decoder_layers ,num_heads=self.num_attention_heads ,relative_attention_num_buckets=self.relative_attention_num_buckets ,dropout_rate=self.dropout_rate ,initializer_factor=self.initializer_factor ,eos_token_id=self.eos_token_id ,bos_token_id=self.pad_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.decoder_start_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[Any] ,A_ : int ,A_ : Dict ,) -> Any: A = UMTaModel(config=A_ ) model.to(A_ ) model.eval() A = model( input_ids=A_ ,decoder_input_ids=A_ ,attention_mask=A_ ,decoder_attention_mask=A_ ,) A = model(input_ids=A_ ,decoder_input_ids=A_ ) A = result.last_hidden_state A = result.past_key_values A = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() ,(self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() ,(self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(A_ ) ,config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) ,4 ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : List[Any] ,A_ : List[str] ,A_ : str ,A_ : List[str] ,A_ : Tuple ,A_ : Union[str, Any] ,) -> Tuple: A = UMTaModel(config=A_ ).get_decoder().to(A_ ).eval() # first forward pass A = model(A_ ,use_cache=A_ ) A = model(A_ ) A = model(A_ ,use_cache=A_ ) self.parent.assertTrue(len(A_ ) == len(A_ ) ) self.parent.assertTrue(len(A_ ) == len(A_ ) + 1 ) A , A = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A = ids_tensor((self.batch_size, 1) ,config.vocab_size ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = model(A_ )['last_hidden_state'] A = model(A_ ,past_key_values=A_ )['last_hidden_state'] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -1, random_slice_idx].detach() A = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Tuple ,A_ : str ,) -> Optional[Any]: A = UMTaModel(config=A_ ).to(A_ ).half().eval() A = model(**A_ )['last_hidden_state'] self.parent.assertFalse(torch.isnan(A_ ).any().item() ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: int = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _lowerCamelCase: Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _lowerCamelCase: List[str] = ( { '''conversational''': UMTaForConditionalGeneration, '''feature-extraction''': UMTaModel, '''summarization''': UMTaForConditionalGeneration, '''text2text-generation''': UMTaForConditionalGeneration, '''translation''': UMTaForConditionalGeneration, '''question-answering''': UMTaForQuestionAnswering, } if is_torch_available() else {} ) _lowerCamelCase: str = True _lowerCamelCase: List[str] = False _lowerCamelCase: str = False _lowerCamelCase: Optional[int] = True _lowerCamelCase: Optional[Any] = True # The small UMT5 model needs higher percentages for CPU/MP tests _lowerCamelCase: Tuple = [0.8, 0.9] def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: A = UMTaModelTester(self ) @unittest.skip('Test has a segmentation fault on torch 1.8.0' ) def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = self.model_tester.prepare_config_and_inputs() A = UMTaModel(config_and_inputs[0] ).to(A_ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( A_ ,(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) ,F'{tmpdirname}/t5_test.onnx' ,export_params=A_ ,opset_version=9 ,input_names=['input_ids', 'decoder_input_ids'] ,) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: A = ['encoder_attentions', 'decoder_attentions', 'cross_attentions'] A = self.model_tester.prepare_config_and_inputs() A = config_and_inputs[0] A = UMTaForConditionalGeneration(A_ ).eval() model.to(A_ ) A = { 'head_mask': torch.zeros(config.num_layers ,config.num_heads ,device=A_ ), 'decoder_head_mask': torch.zeros(config.num_decoder_layers ,config.num_heads ,device=A_ ), 'cross_attn_head_mask': torch.zeros(config.num_decoder_layers ,config.num_heads ,device=A_ ), } for attn_name, (name, mask) in zip(A_ ,head_masking.items() ): A = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": A = torch.ones( config.num_decoder_layers ,config.num_heads ,device=A_ ) A = model.generate( config_and_inputs[1]['input_ids'] ,num_beams=1 ,max_length=3 ,output_attentions=A_ ,return_dict_in_generate=A_ ,**A_ ,) # We check the state of decoder_attentions and cross_attentions just from the last step A = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) ,0.0 ) @unittest.skip('Does not work on the tiny model as we keep hitting edge cases.' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip( 'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged' ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A = UMTaForConditionalGeneration.from_pretrained('google/umt5-small' ,return_dict=A_ ).to(A_ ) A = AutoTokenizer.from_pretrained('google/umt5-small' ,use_fast=A_ ,legacy=A_ ) A = [ 'Bonjour monsieur <extra_id_0> bien <extra_id_1>.', 'No se como puedo <extra_id_0>.', 'This is the reason why we <extra_id_0> them.', 'The <extra_id_0> walks in <extra_id_1>, seats', 'A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.', ] A = tokenizer(A_ ,return_tensors='pt' ,padding=A_ ).input_ids # fmt: off A = torch.tensor( [ [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(A_ ,A_ ) A = model.generate(input_ids.to(A_ ) ) A = [ '<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>', '<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', ] A = tokenizer.batch_decode(A_ ) self.assertEqual(A_ ,A_ )
22
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
1
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : int , snake_case__ : int ): if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) A = number_of_bytes // partitions A = [] for i in range(snake_case__ ): A = i * bytes_per_partition + 1 A = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F'{start_bytes}-{end_bytes}' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''PerceiverFeatureExtractor'''] _lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" def _snake_case ( snake_case__ : list[int] ): if not numbers: return 0 if not isinstance(snake_case__ , (list, tuple) ) or not all( isinstance(snake_case__ , snake_case__ ) for number in numbers ): raise ValueError('numbers must be an iterable of integers' ) A = A = A = numbers[0] for i in range(1 , len(snake_case__ ) ): # update the maximum and minimum subarray products A = numbers[i] if number < 0: A , A = min_till_now, max_till_now A = max(snake_case__ , max_till_now * number ) A = min(snake_case__ , min_till_now * number ) # update the maximum product found till now A = max(snake_case__ , snake_case__ ) return max_prod
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
1
"""simple docstring""" import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Union[str, Any] ) -> Dict: if isinstance(A_ ,A_ ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden A = deepcopy(A_ ) elif os.path.exists(A_ ): with io.open(A_ ,'r' ,encoding='utf-8' ) as f: A = json.load(A_ ) else: try: A = baseaa.urlsafe_baadecode(A_ ).decode('utf-8' ) A = json.loads(A_ ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F'Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}' ) A = config self.set_stage_and_offload() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. A = self.get_value('zero_optimization.stage' ,-1 ) # offload A = False if self.is_zeroa() or self.is_zeroa(): A = set(['cpu', 'nvme'] ) A = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: A = True def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : List[Any] ) -> List[str]: A = self.config # find the config node of interest if it exists A = ds_key_long.split('.' ) A = nodes.pop() for node in nodes: A = config.get(A_ ) if config is None: return None, ds_key return config, ds_key def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : List[str]=None ) -> Optional[int]: A , A = self.find_config_node(A_ ) if config is None: return default return config.get(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[Any] ,A_ : Any=False ) -> Dict: A = self.config # find the config node of interest if it exists A = ds_key_long.split('.' ) for node in nodes: A = config A = config.get(A_ ) if config is None: if must_exist: raise ValueError(F'Can\'t find {ds_key_long} entry in the config: {self.config}' ) else: return # if found remove it if parent_config is not None: parent_config.pop(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> Tuple: A = self.get_value(A_ ) return False if value is None else bool(A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> Union[str, Any]: A = self.get_value(A_ ) return False if value is None else not bool(A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> str: return self._stage == 2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: return self._stage == 3 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: return self._offload class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : str ) -> Union[str, Any]: A = engine def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ,**A_ : int ) -> Tuple: # runs backpropagation and handles mixed precision self.engine.backward(A_ ,**A_ ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : List[Any] ,A_ : str ) -> List[Any]: super().__init__(A_ ,device_placement=A_ ,scaler=A_ ) A = hasattr(self.optimizer ,'overflow' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Dict=None ) -> List[Any]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: if self.__has_overflow__: return self.optimizer.overflow return False class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : List[str] ,A_ : int ,A_ : int ) -> Dict: super().__init__(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class lowerCAmelCase_ : '''simple docstring''' def __init__( self : str ,A_ : str ,A_ : List[str]=0.0_01 ,A_ : Tuple=0 ,**A_ : Tuple ) -> str: A = params A = lr A = weight_decay A = kwargs class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] ,A_ : Dict ,A_ : int=None ,A_ : List[Any]=0 ,**A_ : Optional[int] ) -> Any: A = optimizer A = total_num_steps A = warmup_num_steps A = kwargs
22
"""simple docstring""" from math import pi, sqrt def _snake_case ( snake_case__ : float ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(snake_case__ ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(snake_case__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _snake_case ( ): assert gamma(0.5 ) == sqrt(snake_case__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input('''Gamma of: ''')) print(F"""gamma({num}) = {gamma(num)}""") print('''\nEnter 0 to exit...''')
22
1
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : Union[str, Any]=10 ): A = [] for _ in range(snake_case__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _snake_case ( snake_case__ : List[str] , snake_case__ : Dict=10 ): A = [] for step in range(snake_case__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(snake_case__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , snake_case__ ) A = torch.load(snake_case__ ) scheduler.load_state_dict(snake_case__ ) return lrs @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[Any] ) -> List[str]: self.assertEqual(len(A_ ) ,len(A_ ) ) for a, b in zip(A_ ,A_ ): self.assertAlmostEqual(A_ ,A_ ,delta=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = torch.tensor([0.1, -0.2, -0.1] ,requires_grad=A_ ) A = torch.tensor([0.4, 0.2, -0.5] ) A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping A = AdamW(params=[w] ,lr=2e-1 ,weight_decay=0.0 ) for _ in range(100 ): A = criterion(A_ ,A_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = torch.tensor([0.1, -0.2, -0.1] ,requires_grad=A_ ) A = torch.tensor([0.4, 0.2, -0.5] ) A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping A = Adafactor( params=[w] ,lr=1e-2 ,eps=(1e-30, 1e-3) ,clip_threshold=1.0 ,decay_rate=-0.8 ,betaa=A_ ,weight_decay=0.0 ,relative_step=A_ ,scale_parameter=A_ ,warmup_init=A_ ,) for _ in range(1000 ): A = criterion(A_ ,A_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _lowerCamelCase: Dict = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None _lowerCamelCase: Optional[int] = 10 def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[Any] ,A_ : Dict ,A_ : Dict ,A_ : List[Any]=None ) -> int: self.assertEqual(len(A_ ) ,len(A_ ) ) for a, b in zip(A_ ,A_ ): self.assertAlmostEqual(A_ ,A_ ,delta=A_ ,msg=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) A = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.6_56, 5.6_25, 3.9_06, 2.5, 1.4_06, 0.6_25, 0.1_56], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.1_65, 7.0_71, 6.3_25, 5.7_74, 5.3_45, 5.0, 4.7_14], ), } for scheduler_func, data in scheds.items(): A , A = data A = scheduler_func(self.optimizer ,**A_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) ,1 ) A = unwrap_schedule(A_ ,self.num_steps ) self.assertListAlmostEqual( A_ ,A_ ,tol=1e-2 ,msg=F'failed for {scheduler_func} in normal scheduler' ,) A = scheduler_func(self.optimizer ,**A_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(A_ ) # wrap to test picklability of the schedule A = unwrap_and_save_reload_schedule(A_ ,self.num_steps ) self.assertListEqual(A_ ,A_ ,msg=F'failed for {scheduler_func} in save and reload' ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : Dict ) -> Optional[int]: A = fn def __call__( self : Tuple ,*A_ : List[Any] ,**A_ : str ) -> Optional[Any]: return self.fn(*A_ ,**A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ) -> int: A = list(map(self ,scheduler.lr_lambdas ) )
22
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,A_ : Dict=3 ,A_ : int=3 ,A_ : str=("DownEncoderBlock2D",) ,A_ : Dict=(64,) ,A_ : str=2 ,A_ : Union[str, Any]=32 ,A_ : Optional[int]="silu" ,A_ : str=True ,) -> Union[str, Any]: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Dict ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any]=3 ,A_ : Optional[int]=3 ,A_ : str=("UpDecoderBlock2D",) ,A_ : Any=(64,) ,A_ : Optional[int]=2 ,A_ : Optional[int]=32 ,A_ : Tuple="silu" ,A_ : Optional[int]="group" ,) -> Any: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Union[str, Any]=None ) -> Any: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : List[Any] ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict=None ,A_ : List[Any]="random" ,A_ : Optional[int]=False ,A_ : str=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ) -> Any: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ) -> str: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : str ) -> Union[str, Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Tuple ,A_ : Dict=False ) -> List[str]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple=None ) -> int: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[str] ,A_ : Union[str, Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return self.mean
22
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
"""simple docstring""" def _snake_case ( snake_case__ : list , snake_case__ : list , snake_case__ : int ): A = len(snake_case__ ) A = [[0] * n for i in range(snake_case__ )] for i in range(snake_case__ ): A = y_points[i] for i in range(2 , snake_case__ ): for j in range(snake_case__ , snake_case__ ): A = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
22
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str = field( metadata={'''help''': '''The output directory where the model will be written.'''} , ) _lowerCamelCase: str = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) } , ) _lowerCamelCase: str = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) } , ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def _snake_case ( ): A = HfArgumentParser((ModelArguments,) ) ((A) , ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: A = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: A = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: A = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: A = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed A = True A = True A = 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=snake_case__ , decoder_config=snake_case__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens A = decoder_config.decoder_start_token_id A = decoder_config.pad_token_id if decoder_start_token_id is None: A = decoder_config.bos_token_id if pad_token_id is None: A = decoder_config.eos_token_id # This is necessary to make Flax's generate() work A = decoder_config.eos_token_id A = decoder_start_token_id A = pad_token_id A = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) A = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) A = 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()
22
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[Any] ,A_ : Optional[int]=2 ,A_ : Any=True ,A_ : List[str]=False ,A_ : Tuple=10 ,A_ : List[Any]=3 ,A_ : Any=32 * 8 ,A_ : Dict=32 * 8 ,A_ : List[Any]=4 ,A_ : Tuple=64 ,) -> List[str]: A = parent A = batch_size A = is_training A = use_auxiliary_loss A = num_queries A = num_channels A = min_size A = max_size A = num_labels A = hidden_dim A = hidden_dim def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A_ ) A = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=A_ ) A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=A_ ) > 0.5 ).float() A = (torch.rand((self.batch_size, self.num_labels) ,device=A_ ) > 0.5).long() A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A = self.num_queries A = self.num_labels A = [1, 1, 1, 1] A = self.num_channels A = 64 A = 128 A = self.hidden_dim A = self.hidden_dim A = self.hidden_dim return config def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A , A , A , A , A = self.prepare_config_and_inputs() A = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = output.encoder_hidden_states A = output.pixel_decoder_hidden_states A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : List[str] ,A_ : Union[str, Any]=False ) -> str: with torch.no_grad(): A = MaskaFormerModel(config=A_ ) model.to(A_ ) model.eval() A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ,output_hidden_states=A_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : Any ,A_ : Dict ,A_ : Any ,A_ : Dict ) -> Optional[Any]: A = MaskaFormerForUniversalSegmentation(config=A_ ) model.to(A_ ) model.eval() def comm_check_on_output(A_ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ) comm_check_on_output(A_ ) A = model( pixel_values=A_ ,pixel_mask=A_ ,mask_labels=A_ ,class_labels=A_ ) comm_check_on_output(A_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCamelCase: Optional[Any] = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} _lowerCamelCase: int = False _lowerCamelCase: Dict = False _lowerCamelCase: List[str] = False _lowerCamelCase: int = False def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = MaskaFormerModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) A = inspect.signature(model.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_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A = MaskaFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = (self.model_tester.min_size,) * 2 A = { 'pixel_values': torch.randn((2, 3, *size) ,device=A_ ), 'mask_labels': torch.randn((2, 10, *size) ,device=A_ ), 'class_labels': torch.zeros(2 ,10 ,device=A_ ).long(), } A = self.model_tester.get_config() A = MaskaFormerForUniversalSegmentation(A_ ).to(A_ ) A = model(**A_ ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ).to(A_ ) A = model(**A_ ,output_attentions=A_ ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: if not self.model_tester.is_training: return A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = model_class(A_ ) model.to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = True A = True A = model_class(A_ ).to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ) A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowercase = 1e-4 def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A_ ) A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) A = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) # masks_queries_logits A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] A = torch.tensor(A_ ).to(A_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,A_ ,atol=A_ ) ) # class_queries_logits A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(A_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) A = inputs['pixel_values'].to(A_ ) A = [el.to(A_ ) for el in inputs['mask_labels']] A = [el.to(A_ ) for el in inputs['class_labels']] with torch.no_grad(): A = model(**A_ ) self.assertTrue(outputs.loss is not None )
22
1
"""simple docstring""" from datetime import datetime import requests def _snake_case ( snake_case__ : str ): A = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' A = requests.get(base_url + url ).json()[0]['urls'][0]['src'] return requests.get(snake_case__ ).content if __name__ == "__main__": _lowercase = input('''Enter Video/IGTV url: ''').strip() _lowercase = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4""" with open(file_name, '''wb''') as fp: fp.write(download_video(url)) print(F"""Done. Video saved to disk as {file_name}.""")
22
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any] ,) -> Optional[int]: A = parent A = 13 A = 7 A = True A = True A = True A = 99 A = 32 A = 2 A = 4 A = 37 A = 'gelu' A = 0.1 A = 0.1 A = 512 A = 16 A = 2 A = 0.02 A = 3 A = 4 A = None def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = EsmConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,pad_token_id=1 ,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 ,) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[Any] ,A_ : Any ,A_ : Any ) -> Dict: A = TFEsmModel(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,) -> Optional[int]: A = True A = TFEsmModel(config=A_ ) A = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ,encoder_hidden_states=A_ ) # Also check the case where encoder outputs are not passed A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ) -> Dict: A = TFEsmForMaskedLM(config=A_ ) A = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Optional[int] ) -> Union[str, Any]: A = self.num_labels A = TFEsmForTokenClassification(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _lowerCamelCase: List[str] = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) _lowerCamelCase: Union[str, Any] = False _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: A = TFEsmModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = TFEsmModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: pass @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer A = model.get_bias() assert isinstance(A_ ,A_ ) for k, v in name.items(): assert isinstance(A_ ,tf.Variable ) else: A = model.get_output_embeddings() assert x is None A = model.get_bias() assert name is None @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 1, 2, 3, 4, 5]] ) A = model(A_ )[0] A = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) ,A_ ) # compare the actual values for a slice. A = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-2 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) A = model(A_ )[0] # compare the actual values for a slice. A = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
22
1
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowercase = 6_378_137.0 _lowercase = 6_356_752.314_245 _lowercase = 6_37_81_37 def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): A = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A = atan((1 - flattening) * tan(radians(snake_case__ ) ) ) A = atan((1 - flattening) * tan(radians(snake_case__ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A = haversine_distance(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A = (b_lata + b_lata) / 2 A = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A = (sin(snake_case__ ) ** 2) * (cos(snake_case__ ) ** 2) A = cos(sigma / 2 ) ** 2 A = (sigma - sin(snake_case__ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A = (cos(snake_case__ ) ** 2) * (sin(snake_case__ ) ** 2) A = sin(sigma / 2 ) ** 2 A = (sigma + sin(snake_case__ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
22
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys _lowercase = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') _lowercase = subprocess.check_output(F"""git diff --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() _lowercase = '''|'''.join(sys.argv[1:]) _lowercase = re.compile(rF"""^({joined_dirs}).*?\.py$""") _lowercase = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
22
1
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def _snake_case ( snake_case__ : Callable[[int | float], int | float] , snake_case__ : int | float , snake_case__ : int | float , snake_case__ : int = 100 , ): A = x_start A = fnc(snake_case__ ) A = 0.0 for _ in range(snake_case__ ): # Approximates curve as a sequence of linear lines and sums their length A = (x_end - x_start) / steps + xa A = fnc(snake_case__ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step A = xa A = fxa return length if __name__ == "__main__": def _snake_case ( snake_case__ : Dict ): return math.sin(10 * x ) print('''f(x) = sin(10 * x)''') print('''The length of the curve from x = -10 to x = 10 is:''') _lowercase = 10 while i <= 10_00_00: print(F"""With {i} steps: {line_length(f, -10, 10, i)}""") i *= 10
22
"""simple docstring""" import sys from collections import defaultdict class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ) -> int: A = [] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> Optional[int]: return self.node_position[vertex] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ,A_ : Any ) -> List[Any]: A = pos def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : str ,A_ : Dict ,A_ : List[str] ) -> str: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: A = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: A = 2 * start + 1 else: A = 2 * start + 2 if heap[smallest_child] < heap[start]: A , A = heap[smallest_child], positions[smallest_child] A , A = ( heap[start], positions[start], ) A , A = temp, tempa A = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] ,self.get_position(positions[start] ) ) self.set_position(positions[start] ,A_ ) self.top_to_bottom(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : Dict ,A_ : str ,A_ : Union[str, Any] ) -> Dict: A = position[index] while index != 0: A = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: A = heap[parent] A = position[parent] self.set_position(position[parent] ,A_ ) else: A = val A = temp self.set_position(A_ ,A_ ) break A = parent else: A = val A = temp self.set_position(A_ ,0 ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple ,A_ : Dict ) -> Union[str, Any]: A = len(A_ ) // 2 - 1 for i in range(A_ ,-1 ,-1 ): self.top_to_bottom(A_ ,A_ ,len(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ,A_ : Dict ) -> Union[str, Any]: A = positions[0] A = sys.maxsize self.top_to_bottom(A_ ,0 ,len(A_ ) ,A_ ) return temp def _snake_case ( snake_case__ : Dict ): A = Heap() A = [0] * len(snake_case__ ) A = [-1] * len(snake_case__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph A = [] # Heap of Distance of vertices from their neighboring vertex A = [] for vertex in range(len(snake_case__ ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case__ ) heap.node_position.append(snake_case__ ) A = [] A = 1 A = sys.maxsize for neighbor, distance in adjacency_list[0]: A = 0 A = distance heap.heapify(snake_case__ , snake_case__ ) for _ in range(1 , len(snake_case__ ) ): A = heap.delete_minimum(snake_case__ , snake_case__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) A = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case__ )] ): A = distance heap.bottom_to_top( snake_case__ , heap.get_position(snake_case__ ) , snake_case__ , snake_case__ ) A = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > _lowercase = int(input('''Enter number of edges: ''').strip()) _lowercase = defaultdict(list) for _ in range(edges_number): _lowercase = [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))
22
1
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: A = FlaxMTaForConditionalGeneration.from_pretrained('google/mt5-small' ) A = AutoTokenizer.from_pretrained('google/mt5-small' ) A = tokenizer('Hello there' ,return_tensors='np' ).input_ids A = tokenizer('Hi I am' ,return_tensors='np' ).input_ids A = shift_tokens_right(A_ ,model.config.pad_token_id ,model.config.decoder_start_token_id ) A = model(A_ ,decoder_input_ids=A_ ).logits A = optax.softmax_cross_entropy(A_ ,onehot(A_ ,logits.shape[-1] ) ).mean() A = -(labels.shape[-1] * loss.item()) A = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
22
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter _lowercase = True except ImportError: _lowercase = False _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( snake_case__ : Namespace ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' ,action='store_true' ,help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' ,type=A_ ,help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' ,type=A_ ,help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=A_ ) def __init__( self : Tuple ,A_ : bool ,A_ : str ,A_ : Tuple=None ,*A_ : List[str] ) -> Union[str, Any]: A = testing A = testing_file A = path def _SCREAMING_SNAKE_CASE ( self : int ) -> int: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory A = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(A_ ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) A = ( Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) A = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(A_ ) ) else: with open(self._testing_file ,'r' ) as configuration_file: A = json.load(A_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) ,no_input=A_ ,extra_context=A_ ,) A = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' ,'r' ) as configuration_file: A = json.load(A_ ) A = configuration['lowercase_modelname'] A = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F'{directory}/configuration.json' ) A = 'PyTorch' in generate_tensorflow_pytorch_and_flax A = 'TensorFlow' in generate_tensorflow_pytorch_and_flax A = 'Flax' in generate_tensorflow_pytorch_and_flax A = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(A_ ,exist_ok=A_ ) os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' ,exist_ok=A_ ) # Tests require submodules as they have parent imports with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' ,'w' ): pass shutil.move( F'{directory}/__init__.py' ,F'{model_dir}/__init__.py' ,) shutil.move( F'{directory}/configuration_{lowercase_model_name}.py' ,F'{model_dir}/configuration_{lowercase_model_name}.py' ,) def remove_copy_lines(A_ : int ): with open(A_ ,'r' ) as f: A = f.readlines() with open(A_ ,'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(A_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_{lowercase_model_name}.py' ,F'{model_dir}/modeling_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_tf_{lowercase_model_name}.py' ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_flax_{lowercase_model_name}.py' ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/{lowercase_model_name}.md' ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' ,) shutil.move( F'{directory}/tokenization_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/tokenization_fast_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' ,) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(A_ : str ,A_ : str ,A_ : List[str] ): # Create temp file A , A = mkstemp() A = False with fdopen(A_ ,'w' ) as new_file: with open(A_ ) as old_file: for line in old_file: new_file.write(A_ ) if line_to_copy_below in line: A = True for line_to_copy in lines_to_copy: new_file.write(A_ ) if not line_found: raise ValueError(F'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(A_ ,A_ ) # Remove original file remove(A_ ) # Move new file move(A_ ,A_ ) def skip_units(A_ : Dict ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(A_ : Tuple ): with open(A_ ) as datafile: A = [] A = False A = False for line in datafile: if "# To replace in: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# Below: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(A_ ,A_ ,A_ ) A = [] elif "# Replace with" in line and "##" not in line: A = [] elif "##" not in line: lines_to_copy.append(A_ ) remove(A_ ) replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(A_ )
22
1
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def _snake_case ( snake_case__ : Optional[int] ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' ,type=A_ ,default=A_ ,help='Path to location to store the models' ) download_parser.add_argument( '--force' ,action='store_true' ,help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' ,action='store_true' ,help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' ,) download_parser.add_argument('model' ,type=A_ ,help='Name of the model to download' ) download_parser.set_defaults(func=A_ ) def __init__( self : Dict ,A_ : str ,A_ : str ,A_ : bool ,A_ : bool ) -> Union[str, Any]: A = model A = cache A = force A = trust_remote_code def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code )
22
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : int ,A_ : Tuple ,A_ : str=7 ,A_ : Tuple=3 ,A_ : List[Any]=18 ,A_ : List[str]=30 ,A_ : Optional[Any]=400 ,A_ : Any=True ,A_ : Optional[Any]=None ,A_ : List[str]=True ,) -> str: A = size if size is not None else {'height': 18, 'width': 18} A = parent A = batch_size A = num_channels A = image_size A = min_resolution A = max_resolution A = do_resize A = size A = do_normalize def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04], [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ImageGPTImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ ,'clusters' ) ) self.assertTrue(hasattr(A_ ,'do_resize' ) ) self.assertTrue(hasattr(A_ ,'size' ) ) self.assertTrue(hasattr(A_ ,'do_normalize' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'height': 18, 'width': 18} ) A = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'height': 42, 'width': 42} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: A = self.image_processing_class(**self.image_processor_dict ) A = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,obj[key] ) ) else: self.assertEqual(obj[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(A_ ,'image_processor.json' ) image_processor_first.to_json_file(A_ ) A = self.image_processing_class.from_json_file(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(A_ ) A = self.image_processing_class.from_pretrained(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) @unittest.skip('ImageGPT requires clusters at initialization' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: pass def _snake_case ( ): A = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) A = Image.open(dataset[4]['file'] ) A = Image.open(dataset[5]['file'] ) A = [imagea, imagea] return images @require_vision @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) A = prepare_images() # test non-batched A = image_processing(images[0] ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(1, 1024) ) A = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() ,A_ ) # test batched A = image_processing(A_ ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(2, 1024) ) A = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() ,A_ )
22
1
"""simple docstring""" def _snake_case ( snake_case__ : list , snake_case__ : int , snake_case__ : int = 0 , snake_case__ : int = 0 ): A = right or len(snake_case__ ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(snake_case__ , snake_case__ , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
22
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def _snake_case ( snake_case__ : Optional[int] ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' ,type=A_ ,default=A_ ,help='Path to location to store the models' ) download_parser.add_argument( '--force' ,action='store_true' ,help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' ,action='store_true' ,help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' ,) download_parser.add_argument('model' ,type=A_ ,help='Name of the model to download' ) download_parser.set_defaults(func=A_ ) def __init__( self : Dict ,A_ : str ,A_ : str ,A_ : bool ,A_ : bool ) -> Union[str, Any]: A = model A = cache A = force A = trust_remote_code def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code )
22
1
"""simple docstring""" from __future__ import annotations from typing import Any def _snake_case ( snake_case__ : list[Any] ): create_state_space_tree(snake_case__ , [] , 0 ) def _snake_case ( snake_case__ : list[Any] , snake_case__ : list[Any] , snake_case__ : int ): if index == len(snake_case__ ): print(snake_case__ ) return create_state_space_tree(snake_case__ , snake_case__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(snake_case__ , snake_case__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _lowercase = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['''A''', '''B''', '''C''']) generate_all_subsequences(seq)
22
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''spm_char.model'''} _lowercase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowercase = { '''microsoft/speecht5_asr''': 10_24, '''microsoft/speecht5_tts''': 10_24, '''microsoft/speecht5_vc''': 10_24, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None: A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Any: A = self.__dict__.copy() A = None return state def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]: return self.sp_model.piece_to_id(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]: A = self.sp_model.IdToPiece(A_ ) return token def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: A = [] A = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) A = [1] if token_ids_a is None: return ([0] * len(A_ )) + suffix_ones return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
22
1
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = LEDTokenizer _lowerCamelCase: Optional[int] = LEDTokenizerFast _lowerCamelCase: Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: super().setUp() A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] A = {'unk_token': '<unk>'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,**A_ : int ) -> str: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,**A_ : Any ) -> Union[str, Any]: kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Optional[Any] ) -> Any: return "lower newer", "lower newer" @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: return LEDTokenizer.from_pretrained('allenai/led-base-16384' ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ) -> str: return LEDTokenizerFast.from_pretrained('allenai/led-base-16384' ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] A = [0, 250, 251, 1_7818, 13, 3_9186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = tokenizer(A_ ,max_length=len(A_ ) ,padding=A_ ,return_tensors='pt' ) self.assertIsInstance(A_ ,A_ ) self.assertEqual((2, 9) ,batch.input_ids.shape ) self.assertEqual((2, 9) ,batch.attention_mask.shape ) A = batch.input_ids.tolist()[0] self.assertListEqual(A_ ,A_ ) @require_torch def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = tokenizer(A_ ,padding=A_ ,return_tensors='pt' ) self.assertIn('input_ids' ,A_ ) self.assertIn('attention_mask' ,A_ ) self.assertNotIn('labels' ,A_ ) self.assertNotIn('decoder_attention_mask' ,A_ ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = [ 'Summary of the text.', 'Another summary.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = tokenizer(text_target=A_ ,max_length=32 ,padding='max_length' ,return_tensors='pt' ) self.assertEqual(32 ,targets['input_ids'].shape[1] ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = tokenizer( ['I am a small frog' * 1024, 'I am a small frog'] ,padding=A_ ,truncation=A_ ,return_tensors='pt' ) self.assertIsInstance(A_ ,A_ ) self.assertEqual(batch.input_ids.shape ,(2, 5122) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = ['A long paragraph for summarization.'] A = [ 'Summary of the text.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = tokenizer(A_ ,return_tensors='pt' ) A = tokenizer(text_target=A_ ,return_tensors='pt' ) A = inputs['input_ids'] A = targets['input_ids'] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: A = ['Summary of the text.', 'Another summary.'] A = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] A = tokenizer(A_ ,padding=A_ ) A = [[0] * len(A_ ) for x in encoded_output['input_ids']] A = tokenizer.pad(A_ ) self.assertSequenceEqual(outputs['global_attention_mask'] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: pass def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A = self.rust_tokenizer_class.from_pretrained(A_ ,**A_ ) A = self.tokenizer_class.from_pretrained(A_ ,**A_ ) A = 'A, <mask> AllenNLP sentence.' A = tokenizer_r.encode_plus(A_ ,add_special_tokens=A_ ,return_token_type_ids=A_ ) A = tokenizer_p.encode_plus(A_ ,add_special_tokens=A_ ,return_token_type_ids=A_ ) self.assertEqual(sum(tokens_r['token_type_ids'] ) ,sum(tokens_p['token_type_ids'] ) ) self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) ,sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) ,) A = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) A = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) self.assertSequenceEqual(tokens_p['input_ids'] ,[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] ,[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( A_ ,['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( A_ ,['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger _lowercase = get_logger(__name__) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[str] = None ) -> str: A = ( os.path.join(A_ ,config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) A = Extractor def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : str ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" A = os.path.abspath(A_ ) return os.path.join(self.extract_dir ,hash_url_to_filename(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : str ,A_ : bool ) -> bool: return force_extract or ( not os.path.isfile(A_ ) and not (os.path.isdir(A_ ) and os.listdir(A_ )) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : str ,A_ : bool = False ) -> str: A = self.extractor.infer_extractor_format(A_ ) if not extractor_format: return input_path A = self._get_output_path(A_ ) if self._do_extract(A_ ,A_ ): self.extractor.extract(A_ ,A_ ,A_ ) return output_path class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @classmethod @abstractmethod def _SCREAMING_SNAKE_CASE ( cls : str ,A_ : Union[Path, str] ,**A_ : Union[str, Any] ) -> bool: ... @staticmethod @abstractmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: ... class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: List[bytes] = [] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : int ) -> List[Any]: with open(A_ ,'rb' ) as f: return f.read(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,A_ : Union[Path, str] ,A_ : bytes = b"" ) -> bool: if not magic_number: A = max(len(A_ ) for cls_magic_number in cls.magic_numbers ) try: A = cls.read_magic_number(A_ ,A_ ) except OSError: return False return any(magic_number.startswith(A_ ) for cls_magic_number in cls.magic_numbers ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,A_ : Union[Path, str] ,**A_ : Tuple ) -> bool: return tarfile.is_tarfile(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Dict ,A_ : Optional[Any] ) -> Optional[Any]: def resolved(A_ : str ) -> str: return os.path.realpath(os.path.abspath(A_ ) ) def badpath(A_ : str ,A_ : str ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(A_ ,A_ ) ).startswith(A_ ) def badlink(A_ : Tuple ,A_ : str ) -> bool: # Links are interpreted relative to the directory containing the link A = resolved(os.path.join(A_ ,os.path.dirname(info.name ) ) ) return badpath(info.linkname ,base=A_ ) A = resolved(A_ ) for finfo in members: if badpath(finfo.name ,A_ ): logger.error(F'Extraction of {finfo.name} is blocked (illegal path)' ) elif finfo.issym() and badlink(A_ ,A_ ): logger.error(F'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}' ) elif finfo.islnk() and badlink(A_ ,A_ ): logger.error(F'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}' ) else: yield finfo @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: os.makedirs(A_ ,exist_ok=A_ ) A = tarfile.open(A_ ) tar_file.extractall(A_ ,members=TarExtractor.safemembers(A_ ,A_ ) ) tar_file.close() class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = [B'''\x1F\x8B'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: with gzip.open(A_ ,'rb' ) as gzip_file: with open(A_ ,'wb' ) as extracted_file: shutil.copyfileobj(A_ ,A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : Union[Path, str] ,A_ : bytes = b"" ) -> bool: if super().is_extractable(A_ ,magic_number=A_ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(A_ ,'rb' ) as fp: A = _EndRecData(A_ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: A = fp.read(A_ ) # CD is where we expect it to be if len(A_ ) == sizeCentralDir: A = struct.unpack(A_ ,A_ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: os.makedirs(A_ ,exist_ok=A_ ) with zipfile.ZipFile(A_ ,'r' ) as zip_file: zip_file.extractall(A_ ) zip_file.close() class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: with lzma.open(A_ ) as compressed_file: with open(A_ ,'wb' ) as extracted_file: shutil.copyfileobj(A_ ,A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError('Please pip install rarfile' ) import rarfile os.makedirs(A_ ,exist_ok=A_ ) A = rarfile.RarFile(A_ ) rf.extractall(A_ ) rf.close() class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: str = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError('Please pip install zstandard' ) import zstandard as zstd A = zstd.ZstdDecompressor() with open(A_ ,'rb' ) as ifh, open(A_ ,'wb' ) as ofh: dctx.copy_stream(A_ ,A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = [B'''\x42\x5A\x68'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: with bza.open(A_ ,'rb' ) as compressed_file: with open(A_ ,'wb' ) as extracted_file: shutil.copyfileobj(A_ ,A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError('Please pip install py7zr' ) import pyazr os.makedirs(A_ ,exist_ok=A_ ) with pyazr.SevenZipFile(A_ ,'r' ) as archive: archive.extractall(A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = [B'''\x04\x22\x4D\x18'''] @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : Union[Path, str] ) -> None: if not config.LZ4_AVAILABLE: raise ImportError('Please pip install lz4' ) import lza.frame with lza.frame.open(A_ ,'rb' ) as compressed_file: with open(A_ ,'wb' ) as extracted_file: shutil.copyfileobj(A_ ,A_ ) class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: Dict[str, Type[BaseExtractor]] = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ) -> Union[str, Any]: return max( len(A_ ) for extractor in cls.extractors.values() if issubclass(A_ ,A_ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Union[Path, str] ,A_ : int ) -> List[Any]: try: return MagicNumberBaseExtractor.read_magic_number(A_ ,magic_number_length=A_ ) except OSError: return b"" @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,A_ : Union[Path, str] ,A_ : bool = False ) -> bool: warnings.warn( 'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'infer_extractor_format\' instead.' ,category=A_ ,) A = cls.infer_extractor_format(A_ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,A_ : Union[Path, str] ) -> str: # <Added version="2.4.0"/> A = cls._get_magic_number_max_length() A = cls._read_magic_number(A_ ,A_ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(A_ ,magic_number=A_ ): return extractor_format @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,A_ : Union[Path, str] ,A_ : Union[Path, str] ,A_ : Optional[str] = None ,A_ : Optional[BaseExtractor] = "deprecated" ,) -> None: os.makedirs(os.path.dirname(A_ ) ,exist_ok=A_ ) # Prevent parallel extractions A = str(Path(A_ ).with_suffix('.lock' ) ) with FileLock(A_ ): shutil.rmtree(A_ ,ignore_errors=A_ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(A_ ,A_ ): # passed as positional arg warnings.warn( 'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'extractor_format\' instead.' ,category=A_ ,) A = extractor if extractor != 'deprecated' else extractor_format else: A = cls.extractors[extractor_format] return extractor.extract(A_ ,A_ ) else: warnings.warn( 'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an ' 'exception in 3.0.0.' ,category=A_ ,) for extractor in cls.extractors.values(): if extractor.is_extractable(A_ ): return extractor.extract(A_ ,A_ )
22
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : Optional[Any] ,A_ : Tuple=13 ,A_ : Optional[Any]=7 ,A_ : Dict=True ,A_ : Optional[Any]=True ,A_ : str=True ,A_ : Union[str, Any]=True ,A_ : Optional[Any]=True ,A_ : Tuple=False ,A_ : Optional[int]=False ,A_ : str=False ,A_ : int=2 ,A_ : Union[str, Any]=99 ,A_ : int=0 ,A_ : Dict=32 ,A_ : List[str]=5 ,A_ : Any=4 ,A_ : str=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.02 ,A_ : Optional[Any]=2 ,A_ : List[str]=4 ,A_ : Optional[int]="last" ,A_ : str=True ,A_ : List[str]=None ,A_ : List[Any]=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : List[str] ,A_ : Optional[int] ,) -> Tuple: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ,A_ : Any ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : List[str] ,A_ : List[str] ,) -> Union[str, Any]: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str ,A_ : int ,A_ : str ,A_ : Optional[Any] ,A_ : Any ,A_ : Any ,A_ : Dict ,) -> List[str]: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Dict ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : List[str] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : str ,A_ : Any ,) -> Optional[int]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : str ,) -> List[Any]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[str] ,A_ : Dict ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Dict ,A_ : Any ,) -> Any: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : str ,A_ : int ,A_ : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : int ,) -> Tuple: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: Dict = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Any ,A_ : str ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : str=False ) -> Dict: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : List[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=False ,A_ : Tuple=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Dict ,A_ : Optional[Any] ,A_ : Dict ,A_ : Tuple=False ,A_ : Optional[Any]=1 ) -> List[str]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
22
1
"""simple docstring""" import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values _lowercase = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') _lowercase , _lowercase = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') _lowercase = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: _lowercase = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) _lowercase = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F"""python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
22
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowercase = 8 def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int]=BITS ): A = x.device A = (x * 255).int().clamp(0 , 255 ) A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b c h w -> b c 1 h w' ) A = ((x & mask) != 0).float() A = rearrange(snake_case__ , 'b c d h w -> b (c d) h w' ) A = bits * 2 - 1 return bits def _snake_case ( snake_case__ : Any , snake_case__ : Any=BITS ): A = x.device A = (x > 0).int() A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ , dtype=torch.intaa ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b (c d) h w -> b c d h w' , d=8 ) A = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def _snake_case ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : float = 0.0 , snake_case__ : bool = True , snake_case__ : List[str]=None , snake_case__ : bool = True , ): if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A = self.alphas_cumprod[timestep] A = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A = self._get_variance(snake_case__ , snake_case__ ) A = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A = model_output.device if torch.is_tensor(snake_case__ ) else 'cpu' A = torch.randn(model_output.shape , dtype=model_output.dtype , generator=snake_case__ ).to(snake_case__ ) A = self._get_variance(snake_case__ , snake_case__ ) ** 0.5 * eta * noise A = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) def _snake_case ( self : Dict , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : Tuple="epsilon" , snake_case__ : List[str]=None , snake_case__ : bool = True , ): A = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A , A = torch.split(snake_case__ , sample.shape[1] , dim=1 ) else: A = None # 1. compute alphas, betas A = self.alphas_cumprod[t] A = self.alphas_cumprod[t - 1] if t > 0 else self.one A = 1 - alpha_prod_t A = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A = 0 if t > 0: A = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=snake_case__ ).to(model_output.device ) A = (self._get_variance(snake_case__ , predicted_variance=snake_case__ ) ** 0.5) * noise A = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : UNetaDConditionModel ,A_ : Union[DDIMScheduler, DDPMScheduler] ,A_ : Optional[float] = 1.0 ,) -> Optional[int]: super().__init__() A = bit_scale A = ( ddim_bit_scheduler_step if isinstance(A_ ,A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ ,scheduler=A_ ) @torch.no_grad() def __call__( self : Tuple ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 50 ,A_ : Optional[torch.Generator] = None ,A_ : Optional[int] = 1 ,A_ : Optional[str] = "pil" ,A_ : bool = True ,**A_ : Optional[Any] ,) -> Union[Tuple, ImagePipelineOutput]: A = torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=A_ ,) A = decimal_to_bits(A_ ) * self.bit_scale A = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A = self.unet(A_ ,A_ ).sample # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,A_ ,A_ ).prev_sample A = bits_to_decimal(A_ ) if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
22
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''', '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''', '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''', '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''', '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json''' ), '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''', # See all BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''bert''' def __init__( self : Union[str, Any] ,A_ : Optional[Any]=3_0522 ,A_ : Union[str, Any]=768 ,A_ : Optional[int]=12 ,A_ : Any=12 ,A_ : Any=3072 ,A_ : Any="gelu" ,A_ : Optional[Any]=0.1 ,A_ : str=0.1 ,A_ : Optional[Any]=512 ,A_ : int=2 ,A_ : Tuple=0.02 ,A_ : Any=1e-12 ,A_ : Any=0 ,A_ : Optional[Any]="absolute" ,A_ : Any=True ,A_ : Tuple=None ,**A_ : List[Any] ,) -> str: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = position_embedding_type A = use_cache A = classifier_dropout class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
22
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''yolos''' def __init__( self : Dict ,A_ : Optional[Any]=768 ,A_ : int=12 ,A_ : List[str]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.0 ,A_ : List[Any]=0.0 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : List[Any]=[512, 864] ,A_ : Union[str, Any]=16 ,A_ : List[str]=3 ,A_ : Optional[int]=True ,A_ : Tuple=100 ,A_ : str=True ,A_ : Optional[Any]=False ,A_ : Any=1 ,A_ : Optional[Any]=5 ,A_ : Optional[Any]=2 ,A_ : Optional[int]=5 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.1 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = num_detection_tokens A = use_mid_position_embeddings A = auxiliary_loss # Hungarian matcher A = class_cost A = bbox_cost A = giou_cost # Loss coefficients A = bbox_loss_coefficient A = giou_loss_coefficient A = eos_coefficient class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return 12
22
1
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _snake_case ( ): A = ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=snake_case__ , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=snake_case__ , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=snake_case__ ) return parser.parse_args() def _snake_case ( ): A = parse_args() # Import training_script as a module. A = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) A = script_fpath.stem A = importlib.import_module(snake_case__ ) # Patch sys.argv A = [args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
22
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
1
"""simple docstring""" import math def _snake_case ( snake_case__ : list , snake_case__ : int ): A = len(snake_case__ ) A = int(math.floor(math.sqrt(snake_case__ ) ) ) A = 0 while arr[min(snake_case__ , snake_case__ ) - 1] < x: A = step step += int(math.floor(math.sqrt(snake_case__ ) ) ) if prev >= n: return -1 while arr[prev] < x: A = prev + 1 if prev == min(snake_case__ , snake_case__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": _lowercase = input('''Enter numbers separated by a comma:\n''').strip() _lowercase = [int(item) for item in user_input.split(''',''')] _lowercase = int(input('''Enter the number to be searched:\n''')) _lowercase = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(F"""Number {x} is at index {res}""")
22
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''pixel_values'''] def __init__( self : Optional[Any] ,A_ : bool = True ,A_ : Optional[Dict[str, int]] = None ,A_ : PILImageResampling = PILImageResampling.BILINEAR ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 256} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : float ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[str] ) -> np.ndarray: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Any ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : ImageInput ,A_ : Optional[bool] = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : Optional[bool] = None ,A_ : Optional[float] = None ,A_ : Optional[bool] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Union[str, ChannelDimension] = ChannelDimension.FIRST ,**A_ : Tuple ,) -> List[Any]: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : List[Tuple] = None ) -> str: A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(A_ ): A = target_sizes.numpy() A = [] for idx in range(len(A_ ) ): A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=A_ ) A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: A = logits.argmax(dim=1 ) A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
22
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase = { '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''], '''tokenization_canine''': ['''CanineTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CanineForMultipleChoice''', '''CanineForQuestionAnswering''', '''CanineForSequenceClassification''', '''CanineForTokenClassification''', '''CanineLayer''', '''CanineModel''', '''CaninePreTrainedModel''', '''load_tf_weights_in_canine''', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
1
"""simple docstring""" import unittest from transformers import BertGenerationConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] ,A_ : Any ,A_ : int=13 ,A_ : Optional[int]=7 ,A_ : List[Any]=True ,A_ : str=True ,A_ : Optional[Any]=99 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : str=4 ,A_ : int=37 ,A_ : Optional[Any]="gelu" ,A_ : int=0.1 ,A_ : Dict=0.1 ,A_ : Any=50 ,A_ : Tuple=0.02 ,A_ : Tuple=True ,A_ : Optional[Any]=None ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = vocab_size 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 = max_position_embeddings A = initializer_range A = use_labels A = scope def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = self.get_config() return config, input_ids, input_mask, token_labels def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return BertGenerationConfig( 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 ,is_decoder=A_ ,initializer_range=self.initializer_range ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: ( ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ,A_ : Dict ,A_ : Any ,A_ : Union[str, Any] ,**A_ : int ,) -> List[Any]: A = BertGenerationEncoder(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : str ,A_ : Union[str, Any] ,A_ : int ,A_ : Union[str, Any] ,A_ : Dict ,A_ : int ,**A_ : Union[str, Any] ,) -> int: A = True A = BertGenerationEncoder(config=A_ ) model.to(A_ ) model.eval() A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : Optional[int] ,A_ : Dict ,**A_ : Tuple ,) -> int: A = True A = True A = BertGenerationDecoder(config=A_ ).to(A_ ).eval() # first forward pass A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,use_cache=A_ ,) A = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) ,config.vocab_size ) A = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and A = torch.cat([input_ids, next_tokens] ,dim=-1 ) A = torch.cat([input_mask, next_mask] ,dim=-1 ) A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] A = model( A_ ,attention_mask=A_ ,encoder_hidden_states=A_ ,encoder_attention_mask=A_ ,past_key_values=A_ ,output_hidden_states=A_ ,)['hidden_states'][0] # select random slice A = ids_tensor((1,) ,output_from_past.shape[-1] ).item() A = output_from_no_past[:, -3:, random_slice_idx].detach() A = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : int ,A_ : int ,A_ : List[str] ,*A_ : int ,) -> List[str]: A = BertGenerationDecoder(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A , A , A , A = self.prepare_config_and_inputs() A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: str = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () _lowerCamelCase: Optional[int] = (BertGenerationDecoder,) if is_torch_available() else () _lowerCamelCase: Union[str, Any] = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = BertGenerationEncoderTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: A , A , A , A = self.model_tester.prepare_config_and_inputs() A = 'bert' self.model_tester.create_and_check_model(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: # This regression test was failing with PyTorch < 1.3 ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A = None self.model_tester.create_and_check_model_as_decoder( A_ ,A_ ,A_ ,A_ ,A_ ,A_ ,) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = BertGenerationEncoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = BertGenerationEncoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) A = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): A = model(A_ )[0] A = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape ,A_ ) A = torch.tensor( [[[0.17_75, 0.00_83, -0.03_21], [1.60_02, 0.12_87, 0.39_12], [2.14_73, 0.57_91, 0.60_66]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,A_ ,atol=1e-4 ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = BertGenerationDecoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) A = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): A = model(A_ )[0] A = torch.Size([1, 8, 5_0358] ) self.assertEqual(output.shape ,A_ ) A = torch.tensor( [[[-0.57_88, -2.59_94, -3.70_54], [0.04_38, 4.79_97, 1.87_95], [1.58_62, 6.64_09, 4.46_38]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,A_ ,atol=1e-4 ) )
22
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ) -> int: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Optional[Any]=1 ) -> int: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Dict ) -> Optional[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int=-2 ,A_ : Dict=-1 ) -> str: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Any=-1 ) -> int: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Union[str, Any]=-2 ) -> Optional[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ) -> Any: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ) -> str: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any]=-2 ) -> Any: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple=-2 ,A_ : List[str]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any]=-2 ) -> Dict: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[str]=1 ) -> Dict: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : List[str] ) -> List[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=-2 ,A_ : List[Any]=-1 ) -> int: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int]=-1 ) -> List[Any]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict=-2 ) -> List[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ) -> List[Any]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any]=-2 ,A_ : List[str]=-1 ) -> Any: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any]=-2 ) -> Union[str, Any]: A = time() self.bfs(A_ ) A = time() return end - begin
22
1
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_lowercase ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: str = field(default='''language-modeling''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _lowerCamelCase: ClassVar[Features] = Features({'''text''': Value('''string''' )} ) _lowerCamelCase: ClassVar[Features] = Features({} ) _lowerCamelCase: str = "text" @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, str]: return {self.text_column: "text"}
22
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
1
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''mobilenet_v1''' def __init__( self : str ,A_ : Optional[Any]=3 ,A_ : int=224 ,A_ : int=1.0 ,A_ : Optional[Any]=8 ,A_ : int="relu6" ,A_ : Any=True ,A_ : str=0.9_99 ,A_ : Union[str, Any]=0.02 ,A_ : List[Any]=0.0_01 ,**A_ : Tuple ,) -> int: super().__init__(**A_ ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) A = num_channels A = image_size A = depth_multiplier A = min_depth A = hidden_act A = tf_padding A = classifier_dropout_prob A = initializer_range A = layer_norm_eps class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''PerceiverFeatureExtractor'''] _lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" def _snake_case ( snake_case__ : list[int] , snake_case__ : str ): A = int(snake_case__ ) # Initialize Result A = [] # Traverse through all denomination for denomination in reversed(snake_case__ ): # Find denominations while int(snake_case__ ) >= int(snake_case__ ): total_value -= int(snake_case__ ) answer.append(snake_case__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _lowercase = [] _lowercase = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): _lowercase = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) _lowercase = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter _lowercase = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] _lowercase = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(F"""Following is minimal change for {value}: """) _lowercase = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
1
"""simple docstring""" import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''nvidia/segformer-b0-finetuned-ade-512-512''': ( '''https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json''' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''segformer''' def __init__( self : Any ,A_ : List[Any]=3 ,A_ : str=4 ,A_ : Dict=[2, 2, 2, 2] ,A_ : str=[8, 4, 2, 1] ,A_ : List[Any]=[32, 64, 160, 256] ,A_ : Dict=[7, 3, 3, 3] ,A_ : Optional[int]=[4, 2, 2, 2] ,A_ : int=[1, 2, 5, 8] ,A_ : List[str]=[4, 4, 4, 4] ,A_ : int="gelu" ,A_ : Optional[int]=0.0 ,A_ : str=0.0 ,A_ : Any=0.1 ,A_ : Dict=0.02 ,A_ : List[str]=0.1 ,A_ : List[str]=1e-6 ,A_ : Tuple=256 ,A_ : List[Any]=255 ,**A_ : Any ,) -> Any: super().__init__(**A_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' ,A_ ,) A = num_channels A = num_encoder_blocks A = depths A = sr_ratios A = hidden_sizes A = patch_sizes A = strides A = mlp_ratios A = num_attention_heads A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = classifier_dropout_prob A = initializer_range A = drop_path_rate A = layer_norm_eps A = decoder_hidden_size A = kwargs.get('reshape_last_stage' ,A_ ) A = semantic_loss_ignore_index class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: return 12
22
"""simple docstring""" from math import pi, sqrt def _snake_case ( snake_case__ : float ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(snake_case__ ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(snake_case__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _snake_case ( ): assert gamma(0.5 ) == sqrt(snake_case__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input('''Gamma of: ''')) print(F"""gamma({num}) = {gamma(num)}""") print('''\nEnter 0 to exit...''')
22
1
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = [10, 20, 30, 40, 50, 60] A = [2, 4, 6, 8, 10, 12] A = 100 self.assertEqual(kp.calc_profit(A_ ,A_ ,A_ ) ,210 ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: self.assertRaisesRegex(A_ ,'max_weight must greater than zero.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: self.assertRaisesRegex(A_ ,'Weight can not be negative.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.assertRaisesRegex(A_ ,'Profit can not be negative.' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: self.assertRaisesRegex(A_ ,'max_weight must greater than zero.' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: self.assertRaisesRegex( A_ ,'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
22
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,A_ : Dict=3 ,A_ : int=3 ,A_ : str=("DownEncoderBlock2D",) ,A_ : Dict=(64,) ,A_ : str=2 ,A_ : Union[str, Any]=32 ,A_ : Optional[int]="silu" ,A_ : str=True ,) -> Union[str, Any]: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Dict ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any]=3 ,A_ : Optional[int]=3 ,A_ : str=("UpDecoderBlock2D",) ,A_ : Any=(64,) ,A_ : Optional[int]=2 ,A_ : Optional[int]=32 ,A_ : Tuple="silu" ,A_ : Optional[int]="group" ,) -> Any: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Union[str, Any]=None ) -> Any: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : List[Any] ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict=None ,A_ : List[Any]="random" ,A_ : Optional[int]=False ,A_ : str=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ) -> Any: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ) -> str: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : str ) -> Union[str, Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Tuple ,A_ : Dict=False ) -> List[str]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple=None ) -> int: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[str] ,A_ : Union[str, Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return self.mean
22
1
"""simple docstring""" import copy import re class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: Tuple = '''hp''' _lowerCamelCase: Optional[Any] = {} _lowerCamelCase: Optional[Any] = None @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,A_ : Union[str, Any] ,A_ : Dict ) -> Union[str, Any]: A = prefix A = defaults cls.build_naming_info() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Optional[Any] ,A_ : Optional[int] ) -> List[Any]: if len(A_ ) == 0: return "" A = None if any(char.isdigit() for char in word ): raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A_ ) + 1 ): A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A_ : int ): A = '' while integer != 0: A = chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s A = 0 while True: A = word + '#' + int_to_alphabetic(A_ ) if sword in info["reverse_short_word"]: continue else: A = sword break A = short_word A = word return short_word @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : Any ,A_ : Any ) -> List[str]: A = param_name.split('_' ) A = [TrialShortNamer.shortname_for_word(A_ ,A_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name A = ['', '_'] for separator in separators: A = separator.join(A_ ) if shortname not in info["reverse_short_param"]: A = shortname A = param_name return shortname return param_name @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[Any] ,A_ : List[Any] ) -> Dict: A = TrialShortNamer.shortname_for_key(A_ ,A_ ) A = short_name A = param_name @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ) -> Union[str, Any]: if cls.NAMING_INFO is not None: return A = { 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A_ ,A_ ) A = info @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> Optional[int]: cls.build_naming_info() assert cls.PREFIX is not None A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'You should provide a default value for the param name {k} with value {v}' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue A = cls.NAMING_INFO['short_param'][k] if isinstance(A_ ,A_ ): A = 1 if v else 0 A = '' if isinstance(A_ ,(int, float) ) else '-' A = F'{key}{sep}{v}' name.append(A_ ) return "_".join(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[Any] ) -> Tuple: A = repr[len(cls.PREFIX ) + 1 :] if repr == "": A = [] else: A = repr.split('_' ) A = {} for value in values: if "-" in value: A , A = value.split('-' ) else: A = re.sub('[0-9.]' ,'' ,A_ ) A = float(re.sub('[^0-9.]' ,'' ,A_ ) ) A = cls.NAMING_INFO['reverse_short_param'][p_k] A = p_v for k in cls.DEFAULTS: if k not in parameters: A = cls.DEFAULTS[k] return parameters
22
"""simple docstring""" def _snake_case ( snake_case__ : list , snake_case__ : list , snake_case__ : int ): A = len(snake_case__ ) A = [[0] * n for i in range(snake_case__ )] for i in range(snake_case__ ): A = y_points[i] for i in range(2 , snake_case__ ): for j in range(snake_case__ , snake_case__ ): A = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
22
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase = { '''configuration_conditional_detr''': [ '''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConditionalDetrConfig''', '''ConditionalDetrOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''ConditionalDetrFeatureExtractor'''] _lowercase = ['''ConditionalDetrImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConditionalDetrForObjectDetection''', '''ConditionalDetrForSegmentation''', '''ConditionalDetrModel''', '''ConditionalDetrPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[Any] ,A_ : Optional[int]=2 ,A_ : Any=True ,A_ : List[str]=False ,A_ : Tuple=10 ,A_ : List[Any]=3 ,A_ : Any=32 * 8 ,A_ : Dict=32 * 8 ,A_ : List[Any]=4 ,A_ : Tuple=64 ,) -> List[str]: A = parent A = batch_size A = is_training A = use_auxiliary_loss A = num_queries A = num_channels A = min_size A = max_size A = num_labels A = hidden_dim A = hidden_dim def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A_ ) A = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=A_ ) A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=A_ ) > 0.5 ).float() A = (torch.rand((self.batch_size, self.num_labels) ,device=A_ ) > 0.5).long() A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A = self.num_queries A = self.num_labels A = [1, 1, 1, 1] A = self.num_channels A = 64 A = 128 A = self.hidden_dim A = self.hidden_dim A = self.hidden_dim return config def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A , A , A , A , A = self.prepare_config_and_inputs() A = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = output.encoder_hidden_states A = output.pixel_decoder_hidden_states A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : List[str] ,A_ : Union[str, Any]=False ) -> str: with torch.no_grad(): A = MaskaFormerModel(config=A_ ) model.to(A_ ) model.eval() A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ,output_hidden_states=A_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : Any ,A_ : Dict ,A_ : Any ,A_ : Dict ) -> Optional[Any]: A = MaskaFormerForUniversalSegmentation(config=A_ ) model.to(A_ ) model.eval() def comm_check_on_output(A_ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ) comm_check_on_output(A_ ) A = model( pixel_values=A_ ,pixel_mask=A_ ,mask_labels=A_ ,class_labels=A_ ) comm_check_on_output(A_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCamelCase: Optional[Any] = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} _lowerCamelCase: int = False _lowerCamelCase: Dict = False _lowerCamelCase: List[str] = False _lowerCamelCase: int = False def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = MaskaFormerModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) A = inspect.signature(model.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_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A = MaskaFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = (self.model_tester.min_size,) * 2 A = { 'pixel_values': torch.randn((2, 3, *size) ,device=A_ ), 'mask_labels': torch.randn((2, 10, *size) ,device=A_ ), 'class_labels': torch.zeros(2 ,10 ,device=A_ ).long(), } A = self.model_tester.get_config() A = MaskaFormerForUniversalSegmentation(A_ ).to(A_ ) A = model(**A_ ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ).to(A_ ) A = model(**A_ ,output_attentions=A_ ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: if not self.model_tester.is_training: return A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = model_class(A_ ) model.to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = True A = True A = model_class(A_ ).to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ) A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowercase = 1e-4 def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A_ ) A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) A = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) # masks_queries_logits A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] A = torch.tensor(A_ ).to(A_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,A_ ,atol=A_ ) ) # class_queries_logits A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(A_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) A = inputs['pixel_values'].to(A_ ) A = [el.to(A_ ) for el in inputs['mask_labels']] A = [el.to(A_ ) for el in inputs['class_labels']] with torch.no_grad(): A = model(**A_ ) self.assertTrue(outputs.loss is not None )
22
1
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = (DDPMParallelScheduler,) def _SCREAMING_SNAKE_CASE ( self : Dict ,**A_ : int ) -> Dict: A = { 'num_train_timesteps': 1000, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**A_ ) return config def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] ,[0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=A_ ,beta_end=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: self.check_over_configs(thresholding=A_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=A_ ,prediction_type=A_ ,sample_max_value=A_ ,) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: for t in [0, 500, 999]: self.check_over_forward(time_step=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1e-5 def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = len(A_ ) A = self.dummy_model() A = self.dummy_sample_deter A = self.dummy_sample_deter + 0.1 A = self.dummy_sample_deter - 0.1 A = samplea.shape[0] A = torch.stack([samplea, samplea, samplea] ,dim=0 ) A = torch.arange(A_ )[0:3, None].repeat(1 ,A_ ) A = model(samples.flatten(0 ,1 ) ,timesteps.flatten(0 ,1 ) ) A = scheduler.batch_step_no_noise(A_ ,timesteps.flatten(0 ,1 ) ,samples.flatten(0 ,1 ) ) A = torch.sum(torch.abs(A_ ) ) A = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 11_53.18_33 ) < 1e-2 assert abs(result_mean.item() - 0.50_05 ) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = len(A_ ) A = self.dummy_model() A = self.dummy_sample_deter A = torch.manual_seed(0 ) for t in reversed(range(A_ ) ): # 1. predict noise residual A = model(A_ ,A_ ) # 2. predict previous mean of sample x_t-1 A = scheduler.step(A_ ,A_ ,A_ ,generator=A_ ).prev_sample A = pred_prev_sample A = torch.sum(torch.abs(A_ ) ) A = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 2_58.96_06 ) < 1e-2 assert abs(result_mean.item() - 0.33_72 ) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.scheduler_classes[0] A = self.get_scheduler_config(prediction_type='v_prediction' ) A = scheduler_class(**A_ ) A = len(A_ ) A = self.dummy_model() A = self.dummy_sample_deter A = torch.manual_seed(0 ) for t in reversed(range(A_ ) ): # 1. predict noise residual A = model(A_ ,A_ ) # 2. predict previous mean of sample x_t-1 A = scheduler.step(A_ ,A_ ,A_ ,generator=A_ ).prev_sample A = pred_prev_sample A = torch.sum(torch.abs(A_ ) ) A = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 2_02.02_96 ) < 1e-2 assert abs(result_mean.item() - 0.26_31 ) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=A_ ) A = scheduler.timesteps for i, timestep in enumerate(A_ ): if i == len(A_ ) - 1: A = -1 else: A = timesteps[i + 1] A = scheduler.previous_timestep(A_ ) A = prev_t.item() self.assertEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = [100, 87, 50, 51, 0] with self.assertRaises(A_ ,msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = [100, 87, 50, 1, 0] A = len(A_ ) with self.assertRaises(A_ ,msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=A_ ,timesteps=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**A_ ) A = [scheduler.config.num_train_timesteps] with self.assertRaises( A_ ,msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' ,): scheduler.set_timesteps(timesteps=A_ )
22
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any] ,) -> Optional[int]: A = parent A = 13 A = 7 A = True A = True A = True A = 99 A = 32 A = 2 A = 4 A = 37 A = 'gelu' A = 0.1 A = 0.1 A = 512 A = 16 A = 2 A = 0.02 A = 3 A = 4 A = None def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = EsmConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,pad_token_id=1 ,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 ,) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[Any] ,A_ : Any ,A_ : Any ) -> Dict: A = TFEsmModel(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,) -> Optional[int]: A = True A = TFEsmModel(config=A_ ) A = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ,encoder_hidden_states=A_ ) # Also check the case where encoder outputs are not passed A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ) -> Dict: A = TFEsmForMaskedLM(config=A_ ) A = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Optional[int] ) -> Union[str, Any]: A = self.num_labels A = TFEsmForTokenClassification(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _lowerCamelCase: List[str] = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) _lowerCamelCase: Union[str, Any] = False _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: A = TFEsmModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = TFEsmModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: pass @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer A = model.get_bias() assert isinstance(A_ ,A_ ) for k, v in name.items(): assert isinstance(A_ ,tf.Variable ) else: A = model.get_output_embeddings() assert x is None A = model.get_bias() assert name is None @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 1, 2, 3, 4, 5]] ) A = model(A_ )[0] A = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) ,A_ ) # compare the actual values for a slice. A = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-2 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) A = model(A_ )[0] # compare the actual values for a slice. A = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
22
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : int ): 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__ : Any ): 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__ : Optional[Any] , snake_case__ : int="facebook/mbart-large-en-ro" , snake_case__ : Any=False , snake_case__ : int=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)
22
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys _lowercase = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') _lowercase = subprocess.check_output(F"""git diff --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() _lowercase = '''|'''.join(sys.argv[1:]) _lowercase = re.compile(rF"""^({joined_dirs}).*?\.py$""") _lowercase = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
22
1
"""simple docstring""" import logging import os from .state import PartialState class lowerCAmelCase_ ( logging.LoggerAdapter ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[str] ) -> Optional[int]: A = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Any ,A_ : Dict ,*A_ : int ,**A_ : Dict ) -> Optional[int]: if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' ) A = kwargs.pop('main_process_only' ,A_ ) A = kwargs.pop('in_order' ,A_ ) if self.isEnabledFor(A_ ): if self._should_log(A_ ): A , A = self.process(A_ ,A_ ) self.logger.log(A_ ,A_ ,*A_ ,**A_ ) elif in_order: A = PartialState() for i in range(state.num_processes ): if i == state.process_index: A , A = self.process(A_ ,A_ ) self.logger.log(A_ ,A_ ,*A_ ,**A_ ) state.wait_for_everyone() def _snake_case ( snake_case__ : str , snake_case__ : str = None ): if log_level is None: A = os.environ.get('ACCELERATE_LOG_LEVEL' , snake_case__ ) A = logging.getLogger(snake_case__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(snake_case__ , {} )
22
"""simple docstring""" import sys from collections import defaultdict class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ) -> int: A = [] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> Optional[int]: return self.node_position[vertex] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ,A_ : Any ) -> List[Any]: A = pos def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : str ,A_ : Dict ,A_ : List[str] ) -> str: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: A = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: A = 2 * start + 1 else: A = 2 * start + 2 if heap[smallest_child] < heap[start]: A , A = heap[smallest_child], positions[smallest_child] A , A = ( heap[start], positions[start], ) A , A = temp, tempa A = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] ,self.get_position(positions[start] ) ) self.set_position(positions[start] ,A_ ) self.top_to_bottom(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : Dict ,A_ : str ,A_ : Union[str, Any] ) -> Dict: A = position[index] while index != 0: A = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: A = heap[parent] A = position[parent] self.set_position(position[parent] ,A_ ) else: A = val A = temp self.set_position(A_ ,A_ ) break A = parent else: A = val A = temp self.set_position(A_ ,0 ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple ,A_ : Dict ) -> Union[str, Any]: A = len(A_ ) // 2 - 1 for i in range(A_ ,-1 ,-1 ): self.top_to_bottom(A_ ,A_ ,len(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ,A_ : Dict ) -> Union[str, Any]: A = positions[0] A = sys.maxsize self.top_to_bottom(A_ ,0 ,len(A_ ) ,A_ ) return temp def _snake_case ( snake_case__ : Dict ): A = Heap() A = [0] * len(snake_case__ ) A = [-1] * len(snake_case__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph A = [] # Heap of Distance of vertices from their neighboring vertex A = [] for vertex in range(len(snake_case__ ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case__ ) heap.node_position.append(snake_case__ ) A = [] A = 1 A = sys.maxsize for neighbor, distance in adjacency_list[0]: A = 0 A = distance heap.heapify(snake_case__ , snake_case__ ) for _ in range(1 , len(snake_case__ ) ): A = heap.delete_minimum(snake_case__ , snake_case__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) A = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case__ )] ): A = distance heap.bottom_to_top( snake_case__ , heap.get_position(snake_case__ ) , snake_case__ , snake_case__ ) A = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > _lowercase = int(input('''Enter number of edges: ''').strip()) _lowercase = defaultdict(list) for _ in range(edges_number): _lowercase = [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))
22
1
"""simple docstring""" from __future__ import annotations def _snake_case ( snake_case__ : list[int] ): if len(snake_case__ ) == 0: return array A , A = min(snake_case__ ), max(snake_case__ ) # Compute the variables A = _max - _min + 1 A , A = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: A = i - _min A = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. A = 0 for i in range(snake_case__ ): while holes_repeat[i] > 0: A = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() _lowercase = input('''Enter numbers separated by comma:\n''') _lowercase = [int(x) for x in user_input.split(''',''')] print(pigeon_sort(unsorted))
22
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter _lowercase = True except ImportError: _lowercase = False _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( snake_case__ : Namespace ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' ,action='store_true' ,help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' ,type=A_ ,help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' ,type=A_ ,help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=A_ ) def __init__( self : Tuple ,A_ : bool ,A_ : str ,A_ : Tuple=None ,*A_ : List[str] ) -> Union[str, Any]: A = testing A = testing_file A = path def _SCREAMING_SNAKE_CASE ( self : int ) -> int: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory A = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(A_ ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) A = ( Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) A = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(A_ ) ) else: with open(self._testing_file ,'r' ) as configuration_file: A = json.load(A_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) ,no_input=A_ ,extra_context=A_ ,) A = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' ,'r' ) as configuration_file: A = json.load(A_ ) A = configuration['lowercase_modelname'] A = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F'{directory}/configuration.json' ) A = 'PyTorch' in generate_tensorflow_pytorch_and_flax A = 'TensorFlow' in generate_tensorflow_pytorch_and_flax A = 'Flax' in generate_tensorflow_pytorch_and_flax A = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(A_ ,exist_ok=A_ ) os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' ,exist_ok=A_ ) # Tests require submodules as they have parent imports with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' ,'w' ): pass shutil.move( F'{directory}/__init__.py' ,F'{model_dir}/__init__.py' ,) shutil.move( F'{directory}/configuration_{lowercase_model_name}.py' ,F'{model_dir}/configuration_{lowercase_model_name}.py' ,) def remove_copy_lines(A_ : int ): with open(A_ ,'r' ) as f: A = f.readlines() with open(A_ ,'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(A_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_{lowercase_model_name}.py' ,F'{model_dir}/modeling_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_tf_{lowercase_model_name}.py' ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_flax_{lowercase_model_name}.py' ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/{lowercase_model_name}.md' ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' ,) shutil.move( F'{directory}/tokenization_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/tokenization_fast_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' ,) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(A_ : str ,A_ : str ,A_ : List[str] ): # Create temp file A , A = mkstemp() A = False with fdopen(A_ ,'w' ) as new_file: with open(A_ ) as old_file: for line in old_file: new_file.write(A_ ) if line_to_copy_below in line: A = True for line_to_copy in lines_to_copy: new_file.write(A_ ) if not line_found: raise ValueError(F'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(A_ ,A_ ) # Remove original file remove(A_ ) # Move new file move(A_ ,A_ ) def skip_units(A_ : Dict ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(A_ : Tuple ): with open(A_ ) as datafile: A = [] A = False A = False for line in datafile: if "# To replace in: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# Below: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(A_ ,A_ ,A_ ) A = [] elif "# Replace with" in line and "##" not in line: A = [] elif "##" not in line: lines_to_copy.append(A_ ) remove(A_ ) replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(A_ )
22
1
"""simple docstring""" import unittest from transformers import 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 lowerCAmelCase_ : '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( *A_ : str ,**A_ : Tuple ) -> str: pass @is_pipeline_test @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' ,) A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A = image_classifier(A_ ,candidate_labels=['a', 'b', 'c'] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(A_ ) ,[ [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}], [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'c'}, {'score': 0.3_33, 'label': 'b'}], ] ,) A = image_classifier([image] * 5 ,candidate_labels=['A', 'B', 'C'] ,batch_size=2 ) self.assertEqual( nested_simplify(A_ ) ,[ [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], ] ,) @require_tf def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: A = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' ,framework='tf' ) A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A = image_classifier(A_ ,candidate_labels=['a', 'b', 'c'] ) self.assertEqual( nested_simplify(A_ ) ,[{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}] ,) A = image_classifier([image] * 5 ,candidate_labels=['A', 'B', 'C'] ,batch_size=2 ) self.assertEqual( nested_simplify(A_ ) ,[ [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], [ {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, {'score': 0.3_33, 'label': ANY(A_ )}, ], ] ,) @slow @require_torch def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = pipeline( task='zero-shot-image-classification' ,model='openai/clip-vit-base-patch32' ,) # This is an image of 2 cats with remotes and no planes A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A = image_classifier(A_ ,candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(A_ ) ,[ {'score': 0.5_11, 'label': 'remote'}, {'score': 0.4_85, 'label': 'cat'}, {'score': 0.0_04, 'label': 'plane'}, ] ,) A = image_classifier([image] * 5 ,candidate_labels=['cat', 'plane', 'remote'] ,batch_size=2 ) self.assertEqual( nested_simplify(A_ ) ,[ [ {'score': 0.5_11, 'label': 'remote'}, {'score': 0.4_85, 'label': 'cat'}, {'score': 0.0_04, 'label': 'plane'}, ], ] * 5 ,) @slow @require_tf def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: A = pipeline( task='zero-shot-image-classification' ,model='openai/clip-vit-base-patch32' ,framework='tf' ) # This is an image of 2 cats with remotes and no planes A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A = image_classifier(A_ ,candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(A_ ) ,[ {'score': 0.5_11, 'label': 'remote'}, {'score': 0.4_85, 'label': 'cat'}, {'score': 0.0_04, 'label': 'plane'}, ] ,) A = image_classifier([image] * 5 ,candidate_labels=['cat', 'plane', 'remote'] ,batch_size=2 ) self.assertEqual( nested_simplify(A_ ) ,[ [ {'score': 0.5_11, 'label': 'remote'}, {'score': 0.4_85, 'label': 'cat'}, {'score': 0.0_04, 'label': 'plane'}, ], ] * 5 ,)
22
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : int ,A_ : Tuple ,A_ : str=7 ,A_ : Tuple=3 ,A_ : List[Any]=18 ,A_ : List[str]=30 ,A_ : Optional[Any]=400 ,A_ : Any=True ,A_ : Optional[Any]=None ,A_ : List[str]=True ,) -> str: A = size if size is not None else {'height': 18, 'width': 18} A = parent A = batch_size A = num_channels A = image_size A = min_resolution A = max_resolution A = do_resize A = size A = do_normalize def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04], [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ImageGPTImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ ,'clusters' ) ) self.assertTrue(hasattr(A_ ,'do_resize' ) ) self.assertTrue(hasattr(A_ ,'size' ) ) self.assertTrue(hasattr(A_ ,'do_normalize' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'height': 18, 'width': 18} ) A = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'height': 42, 'width': 42} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: A = self.image_processing_class(**self.image_processor_dict ) A = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,obj[key] ) ) else: self.assertEqual(obj[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(A_ ,'image_processor.json' ) image_processor_first.to_json_file(A_ ) A = self.image_processing_class.from_json_file(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(A_ ) A = self.image_processing_class.from_pretrained(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) @unittest.skip('ImageGPT requires clusters at initialization' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: pass def _snake_case ( ): A = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) A = Image.open(dataset[4]['file'] ) A = Image.open(dataset[5]['file'] ) A = [imagea, imagea] return images @require_vision @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) A = prepare_images() # test non-batched A = image_processing(images[0] ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(1, 1024) ) A = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() ,A_ ) # test batched A = image_processing(A_ ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(2, 1024) ) A = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() ,A_ )
22
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''spm_char.model'''} _lowercase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowercase = { '''microsoft/speecht5_asr''': 10_24, '''microsoft/speecht5_tts''': 10_24, '''microsoft/speecht5_vc''': 10_24, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None: A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Any: A = self.__dict__.copy() A = None return state def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]: return self.sp_model.piece_to_id(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]: A = self.sp_model.IdToPiece(A_ ) return token def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: A = [] A = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) A = [1] if token_ids_a is None: return ([0] * len(A_ )) + suffix_ones return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
22
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def _snake_case ( snake_case__ : Optional[int] ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' ,type=A_ ,default=A_ ,help='Path to location to store the models' ) download_parser.add_argument( '--force' ,action='store_true' ,help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' ,action='store_true' ,help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' ,) download_parser.add_argument('model' ,type=A_ ,help='Name of the model to download' ) download_parser.set_defaults(func=A_ ) def __init__( self : Dict ,A_ : str ,A_ : str ,A_ : bool ,A_ : bool ) -> Union[str, Any]: A = model A = cache A = force A = trust_remote_code def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code )
22
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,A_ : Dict=3 ,A_ : int=3 ,A_ : str=("DownEncoderBlock2D",) ,A_ : Dict=(64,) ,A_ : str=2 ,A_ : Union[str, Any]=32 ,A_ : Optional[int]="silu" ,A_ : str=True ,) -> Union[str, Any]: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Dict ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any]=3 ,A_ : Optional[int]=3 ,A_ : str=("UpDecoderBlock2D",) ,A_ : Any=(64,) ,A_ : Optional[int]=2 ,A_ : Optional[int]=32 ,A_ : Tuple="silu" ,A_ : Optional[int]="group" ,) -> Any: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Union[str, Any]=None ) -> Any: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : List[Any] ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict=None ,A_ : List[Any]="random" ,A_ : Optional[int]=False ,A_ : str=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ) -> Any: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ) -> str: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : str ) -> Union[str, Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Tuple ,A_ : Dict=False ) -> List[str]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple=None ) -> int: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[str] ,A_ : Union[str, Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return self.mean
22
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''spm_char.model'''} _lowercase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowercase = { '''microsoft/speecht5_asr''': 10_24, '''microsoft/speecht5_tts''': 10_24, '''microsoft/speecht5_vc''': 10_24, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None: A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Any: A = self.__dict__.copy() A = None return state def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]: return self.sp_model.piece_to_id(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]: A = self.sp_model.IdToPiece(A_ ) return token def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: A = [] A = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) A = [1] if token_ids_a is None: return ([0] * len(A_ )) + suffix_ones return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
22
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _lowercase = abspath(join(dirname(__file__), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def _snake_case ( snake_case__ : List[Any] ): config.addinivalue_line( 'markers' , 'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested' ) config.addinivalue_line( 'markers' , 'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested' ) config.addinivalue_line('markers' , 'is_pipeline_test: mark test to run only when pipelines are tested' ) config.addinivalue_line('markers' , 'is_staging_test: mark test to run only in the staging environment' ) config.addinivalue_line('markers' , 'accelerate_tests: mark test that require accelerate' ) config.addinivalue_line('markers' , 'tool_tests: mark the tool tests that are run on their specific schedule' ) def _snake_case ( snake_case__ : str ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(snake_case__ ) def _snake_case ( snake_case__ : Union[str, Any] ): from transformers.testing_utils import pytest_terminal_summary_main A = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(snake_case__ , id=snake_case__ ) def _snake_case ( snake_case__ : Any , snake_case__ : Optional[int] ): # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A = 0 # Doctest custom flag to ignore output. _lowercase = doctest.register_optionflag('''IGNORE_RESULT''') _lowercase = doctest.OutputChecker class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Dict ,A_ : int ,A_ : Dict ) -> Tuple: if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self ,A_ ,A_ ,A_ ) _lowercase = CustomOutputChecker _lowercase = HfDoctestModule _lowercase = HfDocTestParser
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _lowercase = float('''nan''') class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : int ) -> Optional[int]: A = sys.stdout A = open(A_ ,'a' ) def __getattr__( self : Union[str, Any] ,A_ : int ) -> List[str]: return getattr(self.stdout ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[Any] ) -> Optional[Any]: self.stdout.write(A_ ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' ,'' ,A_ ,0 ,re.M ) ) def _snake_case ( snake_case__ : List[Any]=80 , snake_case__ : Dict=False ): A = [] # deal with critical env vars A = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: A = os.environ.get(snake_case__ , snake_case__ ) if val is not None: cmd.append(F'{key}={val}' ) # python executable (not always needed if the script is executable) A = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(snake_case__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes A = [] A = '' while len(snake_case__ ) > 0: current_line += F'{cmd.pop(0 )} ' if len(snake_case__ ) == 0 or len(snake_case__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(snake_case__ ) A = '' return "\\\n".join(snake_case__ ) def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[Any] ): # unwrap multi-line input A = re.sub(r'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own A = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F' --output_dir {output_dir}' # ensure we have --overwrite_output_dir A = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _snake_case ( snake_case__ : List[Any] , snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : List[Any] , snake_case__ : Optional[Any] , snake_case__ : List[str] , snake_case__ : Union[str, Any] ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) A = subprocess.run(snake_case__ , capture_output=snake_case__ , text=snake_case__ ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams A = variation.replace(' ' , '-' ) with open(Path(snake_case__ ) / F'log.{prefix}.stdout.txt' , 'w' ) as f: f.write(result.stdout ) with open(Path(snake_case__ ) / F'log.{prefix}.stderr.txt' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'{output_dir}/all_results.json' , 'r' , encoding='utf-8' ) as f: A = json.load(snake_case__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _snake_case ( snake_case__ : Tuple , snake_case__ : str , snake_case__ : List[str] , snake_case__ : Any , snake_case__ : Any , snake_case__ : Union[str, Any] , snake_case__ : Any , snake_case__ : str , snake_case__ : List[str] , snake_case__ : int , ): A = [] A = [] A = F'{id}: {variation:<{longest_variation_len}}' A = F'{preamble}: ' A = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(snake_case__ ) , desc=snake_case__ , leave=snake_case__ ): A = process_run_single( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) A = single_run_metrics[target_metric_key] if not math.isnan(snake_case__ ): metrics.append(snake_case__ ) results.append(snake_case__ ) outcome += "✓" else: outcome += "✘" A = F'\33[2K\r{outcome}' if len(snake_case__ ) > 0: A = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} A = round(mean_metrics[target_metric_key] , 2 ) A = F'{outcome} {mean_target}' if len(snake_case__ ) > 1: results_str += F' {tuple(round(snake_case__ , 2 ) for x in results )}' print(snake_case__ ) A = variation return mean_metrics else: print(snake_case__ ) return {variation_key: variation, target_metric_key: nan} def _snake_case ( ): A = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def _snake_case ( snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : int , snake_case__ : Dict , snake_case__ : List[Any] ): A = pd.DataFrame(snake_case__ ) A = 'variation' A = 'diff_%' A = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan A = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(snake_case__ ): # as a fallback, use the minimal value as the sentinel A = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(snake_case__ ): A = df.apply( lambda snake_case__ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns A = [variation_key, target_metric_key, diff_key, *report_metric_keys] A = df.reindex(snake_case__ , axis='columns' ) # reorder cols # capitalize A = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible A = df.rename(lambda snake_case__ : c.replace('_' , '<br>' ) , axis='columns' ) A = df.rename(lambda snake_case__ : c.replace('_' , '\n' ) , axis='columns' ) A = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=snake_case__ , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=snake_case__ , floatfmt='.2f' )] print('\n\n'.join(snake_case__ ) ) def _snake_case ( ): A = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Base cmd' , ) parser.add_argument( '--variations' , default=snake_case__ , type=snake_case__ , nargs='+' , required=snake_case__ , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=snake_case__ , type=snake_case__ , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=snake_case__ , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=snake_case__ , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=snake_case__ , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=snake_case__ , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) A = parser.parse_args() A = args.output_dir Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) A = get_base_command(snake_case__ , snake_case__ ) # split each dimension into its --foo variations A = [list(map(str.strip , re.split(r'\|' , snake_case__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty A = list(map(str.strip , map(' '.join , itertools.product(*snake_case__ ) ) ) ) A = max(len(snake_case__ ) for x in variations ) # split wanted keys A = args.report_metric_keys.split() # capture prints into a log file for convenience A = F'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(F'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(F'and this script\'s output is also piped into {report_fn}' ) A = Tee(snake_case__ ) print(F'\n*** Running {len(snake_case__ )} benchmarks:' ) print(F'Base command: {" ".join(snake_case__ )}' ) A = 'variation' A = [] for id, variation in enumerate(tqdm(snake_case__ , desc='Total completion: ' , leave=snake_case__ ) ): A = base_cmd + variation.split() results.append( process_run( id + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ , args.target_metric_key , snake_case__ , args.repeat_times , snake_case__ , args.verbose , ) ) process_results(snake_case__ , args.target_metric_key , snake_case__ , args.base_variation , snake_case__ ) if __name__ == "__main__": main()
22
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : Optional[Any] ,A_ : Tuple=13 ,A_ : Optional[Any]=7 ,A_ : Dict=True ,A_ : Optional[Any]=True ,A_ : str=True ,A_ : Union[str, Any]=True ,A_ : Optional[Any]=True ,A_ : Tuple=False ,A_ : Optional[int]=False ,A_ : str=False ,A_ : int=2 ,A_ : Union[str, Any]=99 ,A_ : int=0 ,A_ : Dict=32 ,A_ : List[str]=5 ,A_ : Any=4 ,A_ : str=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.02 ,A_ : Optional[Any]=2 ,A_ : List[str]=4 ,A_ : Optional[int]="last" ,A_ : str=True ,A_ : List[str]=None ,A_ : List[Any]=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : List[str] ,A_ : Optional[int] ,) -> Tuple: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ,A_ : Any ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : List[str] ,A_ : List[str] ,) -> Union[str, Any]: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str ,A_ : int ,A_ : str ,A_ : Optional[Any] ,A_ : Any ,A_ : Any ,A_ : Dict ,) -> List[str]: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Dict ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : List[str] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : str ,A_ : Any ,) -> Optional[int]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : str ,) -> List[Any]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[str] ,A_ : Dict ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Dict ,A_ : Any ,) -> Any: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : str ,A_ : int ,A_ : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : int ,) -> Tuple: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: Dict = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Any ,A_ : str ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : str=False ) -> Dict: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : List[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=False ,A_ : Tuple=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Dict ,A_ : Optional[Any] ,A_ : Dict ,A_ : Tuple=False ,A_ : Optional[Any]=1 ) -> List[str]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
22
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor _lowerCamelCase: torch.FloatTensor _lowerCamelCase: Optional[torch.FloatTensor] = None class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Any = 2 @register_to_config def __init__( self : Optional[int] ,A_ : float = 0.02 ,A_ : float = 100 ,A_ : float = 1.0_07 ,A_ : float = 80 ,A_ : float = 0.05 ,A_ : float = 50 ,) -> List[Any]: # standard deviation of the initial noise distribution A = sigma_max # setable values A = None A = None A = None # sigma(t_i) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : torch.FloatTensor ,A_ : Optional[int] = None ) -> torch.FloatTensor: return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ) -> Optional[Any]: A = num_inference_steps A = np.arange(0 ,self.num_inference_steps )[::-1].copy() A = torch.from_numpy(A_ ).to(A_ ) A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] A = torch.tensor(A_ ,dtype=torch.floataa ,device=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : float ,A_ : Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: if self.config.s_min <= sigma <= self.config.s_max: A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: A = 0 # sample eps ~ N(0, S_noise^2 * I) A = self.config.s_noise * randn_tensor(sample.shape ,generator=A_ ).to(sample.device ) A = sigma + gamma * sigma A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : torch.FloatTensor ,A_ : float ,A_ : float ,A_ : torch.FloatTensor ,A_ : bool = True ,) -> Union[KarrasVeOutput, Tuple]: A = sample_hat + sigma_hat * model_output A = (sample_hat - pred_original_sample) / sigma_hat A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ ,derivative=A_ ,pred_original_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : torch.FloatTensor ,A_ : float ,A_ : float ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : bool = True ,) -> Union[KarrasVeOutput, Tuple]: A = sample_prev + sigma_prev * model_output A = (sample_prev - pred_original_sample) / sigma_prev A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A_ ,derivative=A_ ,pred_original_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[Any] ) -> str: raise NotImplementedError()
22
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowercase = 8 def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int]=BITS ): A = x.device A = (x * 255).int().clamp(0 , 255 ) A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b c h w -> b c 1 h w' ) A = ((x & mask) != 0).float() A = rearrange(snake_case__ , 'b c d h w -> b (c d) h w' ) A = bits * 2 - 1 return bits def _snake_case ( snake_case__ : Any , snake_case__ : Any=BITS ): A = x.device A = (x > 0).int() A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ , dtype=torch.intaa ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b (c d) h w -> b c d h w' , d=8 ) A = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def _snake_case ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : float = 0.0 , snake_case__ : bool = True , snake_case__ : List[str]=None , snake_case__ : bool = True , ): if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A = self.alphas_cumprod[timestep] A = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A = self._get_variance(snake_case__ , snake_case__ ) A = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A = model_output.device if torch.is_tensor(snake_case__ ) else 'cpu' A = torch.randn(model_output.shape , dtype=model_output.dtype , generator=snake_case__ ).to(snake_case__ ) A = self._get_variance(snake_case__ , snake_case__ ) ** 0.5 * eta * noise A = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) def _snake_case ( self : Dict , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : Tuple="epsilon" , snake_case__ : List[str]=None , snake_case__ : bool = True , ): A = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A , A = torch.split(snake_case__ , sample.shape[1] , dim=1 ) else: A = None # 1. compute alphas, betas A = self.alphas_cumprod[t] A = self.alphas_cumprod[t - 1] if t > 0 else self.one A = 1 - alpha_prod_t A = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A = 0 if t > 0: A = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=snake_case__ ).to(model_output.device ) A = (self._get_variance(snake_case__ , predicted_variance=snake_case__ ) ** 0.5) * noise A = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : UNetaDConditionModel ,A_ : Union[DDIMScheduler, DDPMScheduler] ,A_ : Optional[float] = 1.0 ,) -> Optional[int]: super().__init__() A = bit_scale A = ( ddim_bit_scheduler_step if isinstance(A_ ,A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ ,scheduler=A_ ) @torch.no_grad() def __call__( self : Tuple ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 50 ,A_ : Optional[torch.Generator] = None ,A_ : Optional[int] = 1 ,A_ : Optional[str] = "pil" ,A_ : bool = True ,**A_ : Optional[Any] ,) -> Union[Tuple, ImagePipelineOutput]: A = torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=A_ ,) A = decimal_to_bits(A_ ) * self.bit_scale A = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A = self.unet(A_ ,A_ ).sample # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,A_ ,A_ ).prev_sample A = bits_to_decimal(A_ ) if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
22
1
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _snake_case ( snake_case__ : dict ): return (data["data"], data["target"]) def _snake_case ( snake_case__ : np.ndarray , snake_case__ : np.ndarray , snake_case__ : np.ndarray ): A = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(snake_case__ , snake_case__ ) # Predict target for test data A = xgb.predict(snake_case__ ) A = predictions.reshape(len(snake_case__ ) , 1 ) return predictions def _snake_case ( ): A = fetch_california_housing() A , A = data_handling(snake_case__ ) A , A , A , A = train_test_split( snake_case__ , snake_case__ , test_size=0.25 , random_state=1 ) A = xgboost(snake_case__ , snake_case__ , snake_case__ ) # Error printing print(F'Mean Absolute Error : {mean_absolute_error(snake_case__ , snake_case__ )}' ) print(F'Mean Square Error : {mean_squared_error(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
22
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''yolos''' def __init__( self : Dict ,A_ : Optional[Any]=768 ,A_ : int=12 ,A_ : List[str]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.0 ,A_ : List[Any]=0.0 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : List[Any]=[512, 864] ,A_ : Union[str, Any]=16 ,A_ : List[str]=3 ,A_ : Optional[int]=True ,A_ : Tuple=100 ,A_ : str=True ,A_ : Optional[Any]=False ,A_ : Any=1 ,A_ : Optional[Any]=5 ,A_ : Optional[Any]=2 ,A_ : Optional[int]=5 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.1 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = num_detection_tokens A = use_mid_position_embeddings A = auxiliary_loss # Hungarian matcher A = class_cost A = bbox_cost A = giou_cost # Loss coefficients A = bbox_loss_coefficient A = giou_loss_coefficient A = eos_coefficient class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return 12
22
1
"""simple docstring""" import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency _lowercase = { '''E''': 12.70, '''T''': 9.06, '''A''': 8.17, '''O''': 7.51, '''I''': 6.97, '''N''': 6.75, '''S''': 6.33, '''H''': 6.09, '''R''': 5.99, '''D''': 4.25, '''L''': 4.03, '''C''': 2.78, '''U''': 2.76, '''M''': 2.41, '''W''': 2.36, '''F''': 2.23, '''G''': 2.02, '''Y''': 1.97, '''P''': 1.93, '''B''': 1.29, '''V''': 0.98, '''K''': 0.77, '''J''': 0.15, '''X''': 0.15, '''Q''': 0.10, '''Z''': 0.07, } _lowercase = '''ETAOINSHRDLCUMWFGYPBVKJXQZ''' _lowercase = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def _snake_case ( snake_case__ : str ): A = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _snake_case ( snake_case__ : tuple ): return x[0] def _snake_case ( snake_case__ : str ): A = get_letter_count(snake_case__ ) A = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(snake_case__ ) A = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=snake_case__ ) A = ''.join(freq_to_letter[freq] ) A = list(freq_to_letter_str.items() ) freq_pairs.sort(key=snake_case__ , reverse=snake_case__ ) A = [freq_pair[1] for freq_pair in freq_pairs] return "".join(snake_case__ ) def _snake_case ( snake_case__ : str ): A = get_frequency_order(snake_case__ ) A = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
22
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
1
"""simple docstring""" def _snake_case ( snake_case__ : str ): A = [int(snake_case__ ) for i in ip_va_address.split('.' ) if i.isdigit()] return len(snake_case__ ) == 4 and all(0 <= int(snake_case__ ) <= 254 for octet in octets ) if __name__ == "__main__": _lowercase = input().strip() _lowercase = '''valid''' if is_ip_va_address_valid(ip) else '''invalid''' print(F"""{ip} is a {valid_or_invalid} IP v4 address.""")
22
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''pixel_values'''] def __init__( self : Optional[Any] ,A_ : bool = True ,A_ : Optional[Dict[str, int]] = None ,A_ : PILImageResampling = PILImageResampling.BILINEAR ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 256} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : float ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[str] ) -> np.ndarray: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Any ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : ImageInput ,A_ : Optional[bool] = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : Optional[bool] = None ,A_ : Optional[float] = None ,A_ : Optional[bool] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Union[str, ChannelDimension] = ChannelDimension.FIRST ,**A_ : Tuple ,) -> List[Any]: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : List[Tuple] = None ) -> str: A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(A_ ): A = target_sizes.numpy() A = [] for idx in range(len(A_ ) ): A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=A_ ) A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: A = logits.argmax(dim=1 ) A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
22
1
"""simple docstring""" import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : DatasetDict , snake_case__ : List[int] , snake_case__ : List[int] , snake_case__ : int = 16 ): A = AutoTokenizer.from_pretrained('bert-base-cased' ) A = DatasetDict( { 'train': dataset['train'].select(snake_case__ ), 'validation': dataset['train'].select(snake_case__ ), 'test': dataset['validation'], } ) def tokenize_function(snake_case__ : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : Optional[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. A = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A = 16 elif accelerator.mixed_precision != "no": A = 8 else: A = None return tokenizer.pad( snake_case__ , padding='longest' , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors='pt' , ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['test'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader, test_dataloader def _snake_case ( snake_case__ : str , snake_case__ : List[str] ): # New Code # A = [] # Download the dataset A = load_dataset('glue' , 'mrpc' ) # Create our splits A = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator A = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation A = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: A = batch_size // MAX_GPU_BATCH_SIZE A = MAX_GPU_BATCH_SIZE set_seed(snake_case__ ) # New Code # # Create our folds: A = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) A = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(snake_case__ ): A , A , A = get_fold_dataloaders( snake_case__ , snake_case__ , snake_case__ , snake_case__ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A = model.to(accelerator.device ) # Instantiate optimizer A = AdamW(params=model.parameters() , lr=snake_case__ ) # Instantiate scheduler A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=100 , num_training_steps=(len(snake_case__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) A , A = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) # New Code # # We also run predictions on the test set at the very end A = [] for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits A , A = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(snake_case__ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: A = torch.cat(snake_case__ , dim=0 ) A = torch.stack(snake_case__ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) A = metric.compute(predictions=snake_case__ , references=snake_case__ ) accelerator.print('Average test metrics from all folds:' , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=snake_case__ , default=snake_case__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=snake_case__ , default=3 , help='The number of splits to perform across the dataset' ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
22
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
1
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _snake_case ( ): raise RuntimeError('CUDA out of memory.' ) class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Dict ) -> Any: super().__init__() A = nn.Linear(3 ,4 ) A = nn.BatchNormad(4 ) A = nn.Linear(4 ,5 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> List[str]: return self.lineara(self.batchnorm(self.lineara(A_ ) ) ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: A = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(A_ : Optional[int] ): nonlocal batch_sizes batch_sizes.append(A_ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(A_ ,[128, 64, 32, 16, 8] ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(A_ : int ,A_ : Optional[int] ): nonlocal batch_sizes batch_sizes.append(A_ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga A , A = mock_training_loop_function('hello' ) self.assertListEqual(A_ ,[128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] ,[8, 'hello'] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(A_ : List[str] ): pass with self.assertRaises(A_ ) as cm: mock_training_loop_function() self.assertIn('No executable batch size found, reached zero.' ,cm.exception.args[0] ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(A_ : Tuple ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(A_ ) as cm: mock_training_loop_function() self.assertIn('No executable batch size found, reached zero.' ,cm.exception.args[0] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(A_ : Any ,A_ : Any ,A_ : str ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(A_ ) as cm: mock_training_loop_function(128 ,'hello' ,'world' ) self.assertIn('Batch size was passed into `f`' ,cm.exception.args[0] ) self.assertIn('`f(arg1=\'hello\', arg2=\'world\')' ,cm.exception.args[0] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(A_ : Optional[Any] ): raise ValueError('Oops, we had an error!' ) with self.assertRaises(A_ ) as cm: mock_training_loop_function() self.assertIn('Oops, we had an error!' ,cm.exception.args[0] ) @require_cuda def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: A = torch.cuda.memory_allocated() A = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() ,A_ ) A = release_memory(A_ ) self.assertEqual(torch.cuda.memory_allocated() ,A_ )
22
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ) -> int: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Optional[Any]=1 ) -> int: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Dict ) -> Optional[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int=-2 ,A_ : Dict=-1 ) -> str: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Any=-1 ) -> int: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Union[str, Any]=-2 ) -> Optional[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ) -> Any: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ) -> str: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any]=-2 ) -> Any: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple=-2 ,A_ : List[str]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any]=-2 ) -> Dict: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[str]=1 ) -> Dict: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : List[str] ) -> List[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=-2 ,A_ : List[Any]=-1 ) -> int: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int]=-1 ) -> List[Any]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict=-2 ) -> List[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ) -> List[Any]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any]=-2 ,A_ : List[str]=-1 ) -> Any: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any]=-2 ) -> Union[str, Any]: A = time() self.bfs(A_ ) A = time() return end - begin
22
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: A = tempfile.mkdtemp() A = BlipImageProcessor() A = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel' ) A = BlipProcessor(A_ ,A_ ) processor.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : int ,**A_ : Dict ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname ,**A_ ).tokenizer def _SCREAMING_SNAKE_CASE ( self : List[Any] ,**A_ : Tuple ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname ,**A_ ).image_processor def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] A = [Image.fromarray(np.moveaxis(A_ ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: A = BlipProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' ) A = self.get_image_processor(do_normalize=A_ ,padding_value=1.0 ) A = BlipProcessor.from_pretrained( self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=A_ ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A_ ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipProcessor(tokenizer=A_ ,image_processor=A_ ) A = self.prepare_image_inputs() A = image_processor(A_ ,return_tensors='np' ) A = processor(images=A_ ,return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = processor(text=A_ ) A = tokenizer(A_ ,return_token_type_ids=A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: A = self.get_image_processor() A = self.get_tokenizer() A = BlipProcessor(tokenizer=A_ ,image_processor=A_ ) A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A = processor.batch_decode(A_ ) A = tokenizer.batch_decode(A_ ) self.assertListEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Any: A = self.get_image_processor() A = self.get_tokenizer() A = BlipProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'input_ids', 'attention_mask'] )
22
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowercase = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''PerceiverFeatureExtractor'''] _lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : Union[str, Any] ): A = SwinConfig( embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['stage2', 'stage3', 'stage4'] , ) A = DetaConfig( backbone_config=snake_case__ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=snake_case__ , with_box_refine=snake_case__ , two_stage=snake_case__ , ) # set labels A = 'huggingface/label-files' if "o365" in model_name: A = 366 A = 'object365-id2label.json' else: A = 91 A = 'coco-detection-id2label.json' A = num_labels A = json.load(open(cached_download(hf_hub_url(snake_case__ , snake_case__ , repo_type='dataset' ) ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} return config def _snake_case ( snake_case__ : Optional[Any] ): A = [] # stem # fmt: off rename_keys.append(('backbone.0.body.patch_embed.proj.weight', 'model.backbone.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.0.body.patch_embed.proj.bias', 'model.backbone.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.0.body.patch_embed.norm.weight', 'model.backbone.model.embeddings.norm.weight') ) rename_keys.append(('backbone.0.body.patch_embed.norm.bias', 'model.backbone.model.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm1.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm1.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm2.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm2.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias') ) if i < 3: rename_keys.append((F'backbone.0.body.layers.{i}.downsample.reduction.weight', F'model.backbone.model.encoder.layers.{i}.downsample.reduction.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.downsample.norm.weight', F'model.backbone.model.encoder.layers.{i}.downsample.norm.weight') ) rename_keys.append((F'backbone.0.body.layers.{i}.downsample.norm.bias', F'model.backbone.model.encoder.layers.{i}.downsample.norm.bias') ) rename_keys.append(('backbone.0.body.norm1.weight', 'model.backbone.model.hidden_states_norms.stage2.weight') ) rename_keys.append(('backbone.0.body.norm1.bias', 'model.backbone.model.hidden_states_norms.stage2.bias') ) rename_keys.append(('backbone.0.body.norm2.weight', 'model.backbone.model.hidden_states_norms.stage3.weight') ) rename_keys.append(('backbone.0.body.norm2.bias', 'model.backbone.model.hidden_states_norms.stage3.bias') ) rename_keys.append(('backbone.0.body.norm3.weight', 'model.backbone.model.hidden_states_norms.stage4.weight') ) rename_keys.append(('backbone.0.body.norm3.bias', 'model.backbone.model.hidden_states_norms.stage4.bias') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight', F'model.encoder.layers.{i}.self_attn.sampling_offsets.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias', F'model.encoder.layers.{i}.self_attn.sampling_offsets.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.weight', F'model.encoder.layers.{i}.self_attn.attention_weights.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.bias', F'model.encoder.layers.{i}.self_attn.attention_weights.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.weight', F'model.encoder.layers.{i}.self_attn.value_proj.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.bias', F'model.encoder.layers.{i}.self_attn.value_proj.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.weight', F'model.encoder.layers.{i}.self_attn.output_proj.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.bias', F'model.encoder.layers.{i}.self_attn.output_proj.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm1.weight', F'model.encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'model.encoder.layers.{i}.self_attn_layer_norm.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'model.encoder.layers.{i}.fc1.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'model.encoder.layers.{i}.fc1.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'model.encoder.layers.{i}.fc2.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'model.encoder.layers.{i}.fc2.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'model.encoder.layers.{i}.final_layer_norm.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'model.encoder.layers.{i}.final_layer_norm.bias') ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.weight', F'model.decoder.layers.{i}.encoder_attn.attention_weights.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.bias', F'model.decoder.layers.{i}.encoder_attn.attention_weights.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.weight', F'model.decoder.layers.{i}.encoder_attn.value_proj.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.bias', F'model.decoder.layers.{i}.encoder_attn.value_proj.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.weight', F'model.decoder.layers.{i}.encoder_attn.output_proj.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.bias', F'model.decoder.layers.{i}.encoder_attn.output_proj.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm1.weight', F'model.decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'model.decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'model.decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'model.decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm2.weight', F'model.decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm2.bias', F'model.decoder.layers.{i}.self_attn_layer_norm.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'model.decoder.layers.{i}.fc1.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'model.decoder.layers.{i}.fc1.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'model.decoder.layers.{i}.fc2.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'model.decoder.layers.{i}.fc2.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'model.decoder.layers.{i}.final_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'model.decoder.layers.{i}.final_layer_norm.bias') ) # fmt: on return rename_keys def _snake_case ( snake_case__ : Dict , snake_case__ : str , snake_case__ : str ): A = dct.pop(snake_case__ ) A = val def _snake_case ( snake_case__ : List[str] , snake_case__ : str ): A = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): A = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) A = state_dict.pop(F'backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight' ) A = state_dict.pop(F'backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A = in_proj_weight[:dim, :] A = in_proj_bias[: dim] A = in_proj_weight[ dim : dim * 2, : ] A = in_proj_bias[ dim : dim * 2 ] A = in_proj_weight[ -dim :, : ] A = in_proj_bias[-dim :] # fmt: on def _snake_case ( snake_case__ : List[Any] , snake_case__ : Union[str, Any] ): # transformer decoder self-attention layers A = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention A = state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_weight' ) A = state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict A = in_proj_weight[:hidden_size, :] A = in_proj_bias[:hidden_size] A = in_proj_weight[ hidden_size : hidden_size * 2, : ] A = in_proj_bias[hidden_size : hidden_size * 2] A = in_proj_weight[-hidden_size:, :] A = in_proj_bias[-hidden_size:] def _snake_case ( ): A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def _snake_case ( snake_case__ : List[str] , snake_case__ : Union[str, Any] , snake_case__ : List[Any] ): A = get_deta_config(snake_case__ ) # load original state dict if model_name == "deta-swin-large": A = hf_hub_download(repo_id='nielsr/deta-checkpoints' , filename='adet_swin_ft.pth' ) elif model_name == "deta-swin-large-o365": A = hf_hub_download(repo_id='jozhang97/deta-swin-l-o365' , filename='deta_swin_pt_o365.pth' ) else: raise ValueError(F'Model name {model_name} not supported' ) A = torch.load(snake_case__ , map_location='cpu' )['model'] # original state dict for name, param in state_dict.items(): print(snake_case__ , param.shape ) # rename keys A = create_rename_keys(snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_swin_q_k_v(snake_case__ , config.backbone_config ) read_in_decoder_q_k_v(snake_case__ , snake_case__ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: A = state_dict.pop(snake_case__ ) A = val if "input_proj" in key: A = state_dict.pop(snake_case__ ) A = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: A = state_dict.pop(snake_case__ ) A = val # finally, create HuggingFace model and load state dict A = DetaForObjectDetection(snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() A = 'cuda' if torch.cuda.is_available() else 'cpu' model.to(snake_case__ ) # load image processor A = DetaImageProcessor(format='coco_detection' ) # verify our conversion on image A = prepare_img() A = processor(images=snake_case__ , return_tensors='pt' ) A = encoding['pixel_values'] A = model(pixel_values.to(snake_case__ ) ) # verify logits print('Logits:' , outputs.logits[0, :3, :3] ) print('Boxes:' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": A = torch.tensor( [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] ) A = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] ) elif model_name == "deta-swin-large-o365": A = torch.tensor( [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] ) A = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(snake_case__ ) , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(snake_case__ ) , atol=1e-4 ) print('Everything ok!' ) if pytorch_dump_folder_path: # Save model and processor logger.info(F'Saving PyTorch model and processor to {pytorch_dump_folder_path}...' ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) model.save_pretrained(snake_case__ ) processor.save_pretrained(snake_case__ ) # Push to hub if push_to_hub: print('Pushing model and processor to hub...' ) model.push_to_hub(F'jozhang97/{model_name}' ) processor.push_to_hub(F'jozhang97/{model_name}' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument( '''--model_name''', type=str, default='''deta-swin-large''', choices=['''deta-swin-large''', '''deta-swin-large-o365'''], help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _lowercase = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
22
"""simple docstring""" from math import pi, sqrt def _snake_case ( snake_case__ : float ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(snake_case__ ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(snake_case__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _snake_case ( ): assert gamma(0.5 ) == sqrt(snake_case__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input('''Gamma of: ''')) print(F"""gamma({num}) = {gamma(num)}""") print('''\nEnter 0 to exit...''')
22
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = tempfile.mkdtemp() A = BlipImageProcessor() A = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) A = BlipaProcessor(A_ ,A_ ) processor.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : Dict ,**A_ : Optional[int] ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname ,**A_ ).tokenizer def _SCREAMING_SNAKE_CASE ( self : Dict ,**A_ : Dict ) -> List[Any]: return AutoProcessor.from_pretrained(self.tmpdirname ,**A_ ).image_processor def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] A = [Image.fromarray(np.moveaxis(A_ ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : int ) -> Any: A = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' ) A = self.get_image_processor(do_normalize=A_ ,padding_value=1.0 ) A = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=A_ ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A_ ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.get_image_processor() A = self.get_tokenizer() A = BlipaProcessor(tokenizer=A_ ,image_processor=A_ ) A = self.prepare_image_inputs() A = image_processor(A_ ,return_tensors='np' ) A = processor(images=A_ ,return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipaProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = processor(text=A_ ) A = tokenizer(A_ ,return_token_type_ids=A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: A = self.get_image_processor() A = self.get_tokenizer() A = BlipaProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipaProcessor(tokenizer=A_ ,image_processor=A_ ) A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A = processor.batch_decode(A_ ) A = tokenizer.batch_decode(A_ ) self.assertListEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.get_image_processor() A = self.get_tokenizer() A = BlipaProcessor(tokenizer=A_ ,image_processor=A_ ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=A_ ,images=A_ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'input_ids', 'attention_mask'] )
22
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] ,A_ : Dict=3 ,A_ : int=3 ,A_ : str=("DownEncoderBlock2D",) ,A_ : Dict=(64,) ,A_ : str=2 ,A_ : Union[str, Any]=32 ,A_ : Optional[int]="silu" ,A_ : str=True ,) -> Union[str, Any]: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Dict ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any]=3 ,A_ : Optional[int]=3 ,A_ : str=("UpDecoderBlock2D",) ,A_ : Any=(64,) ,A_ : Optional[int]=2 ,A_ : Optional[int]=32 ,A_ : Tuple="silu" ,A_ : Optional[int]="group" ,) -> Any: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : Union[str, Any]=None ) -> Any: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : List[Any] ): def custom_forward(*A_ : Tuple ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : Optional[int] ,A_ : Any ,A_ : str ,A_ : Dict=None ,A_ : List[Any]="random" ,A_ : Optional[int]=False ,A_ : str=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ) -> Any: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ) -> List[Any]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ) -> str: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : str ) -> Union[str, Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Tuple ,A_ : Dict=False ) -> List[str]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple=None ) -> int: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : List[str] ,A_ : Union[str, Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return self.mean
22
1
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def _snake_case ( ): A = { 'repo_name': ['test_repo1', 'test_repo2', 'test_repo3'], 'path': ['test_1.py', 'test_2.py', 'unit_test.py'], 'content': ['a ' * 20, 'a ' * 30, 'b ' * 7], } A = Dataset.from_dict(snake_case__ ) return dataset class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: A = get_dataset() A = make_duplicate_clusters(A_ ,0.85 ) self.assertEqual(len(duplicate_clusters[0] ) ,2 ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = get_dataset() A , A = deduplicate_dataset(A_ ) self.assertEqual(len(A_ ) ,2 ) print(A_ ) self.assertEqual(duplicate_clusters[0][0]['copies'] ,2 ) self.assertEqual(duplicate_clusters[0][0]['is_extreme'] ,A_ )
22
"""simple docstring""" def _snake_case ( snake_case__ : list , snake_case__ : list , snake_case__ : int ): A = len(snake_case__ ) A = [[0] * n for i in range(snake_case__ )] for i in range(snake_case__ ): A = y_points[i] for i in range(2 , snake_case__ ): for j in range(snake_case__ , snake_case__ ): A = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
22
1
"""simple docstring""" from __future__ import annotations import bisect def _snake_case ( snake_case__ : list[int] , snake_case__ : int , snake_case__ : int = 0 , snake_case__ : int = -1 ): if hi < 0: A = len(snake_case__ ) while lo < hi: A = lo + (hi - lo) // 2 if sorted_collection[mid] < item: A = mid + 1 else: A = mid return lo def _snake_case ( snake_case__ : list[int] , snake_case__ : int , snake_case__ : int = 0 , snake_case__ : int = -1 ): if hi < 0: A = len(snake_case__ ) while lo < hi: A = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: A = mid + 1 else: A = mid return lo def _snake_case ( snake_case__ : list[int] , snake_case__ : int , snake_case__ : int = 0 , snake_case__ : int = -1 ): sorted_collection.insert(bisect_left(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) , snake_case__ ) def _snake_case ( snake_case__ : list[int] , snake_case__ : int , snake_case__ : int = 0 , snake_case__ : int = -1 ): sorted_collection.insert(bisect_right(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) , snake_case__ ) def _snake_case ( snake_case__ : list[int] , snake_case__ : int ): A = 0 A = len(snake_case__ ) - 1 while left <= right: A = left + (right - left) // 2 A = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: A = midpoint - 1 else: A = midpoint + 1 return None def _snake_case ( snake_case__ : list[int] , snake_case__ : int ): A = bisect.bisect_left(snake_case__ , snake_case__ ) if index != len(snake_case__ ) and sorted_collection[index] == item: return index return None def _snake_case ( snake_case__ : list[int] , snake_case__ : int , snake_case__ : int , snake_case__ : int ): if right < left: return None A = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(snake_case__ , snake_case__ , snake_case__ , midpoint - 1 ) else: return binary_search_by_recursion(snake_case__ , snake_case__ , midpoint + 1 , snake_case__ ) if __name__ == "__main__": _lowercase = input('''Enter numbers separated by comma:\n''').strip() _lowercase = sorted(int(item) for item in user_input.split(''',''')) _lowercase = int(input('''Enter a single number to be found in the list:\n''')) _lowercase = 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}.""")
22
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : Optional[Any] ,A_ : Optional[int]=2 ,A_ : Any=True ,A_ : List[str]=False ,A_ : Tuple=10 ,A_ : List[Any]=3 ,A_ : Any=32 * 8 ,A_ : Dict=32 * 8 ,A_ : List[Any]=4 ,A_ : Tuple=64 ,) -> List[str]: A = parent A = batch_size A = is_training A = use_auxiliary_loss A = num_queries A = num_channels A = min_size A = max_size A = num_labels A = hidden_dim A = hidden_dim def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( A_ ) A = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=A_ ) A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=A_ ) > 0.5 ).float() A = (torch.rand((self.batch_size, self.num_labels) ,device=A_ ) > 0.5).long() A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: A = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A = self.num_queries A = self.num_labels A = [1, 1, 1, 1] A = self.num_channels A = 64 A = 128 A = self.hidden_dim A = self.hidden_dim A = self.hidden_dim return config def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A , A , A , A , A = self.prepare_config_and_inputs() A = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ) -> Union[str, Any]: A = output.encoder_hidden_states A = output.pixel_decoder_hidden_states A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(A_ ) ,config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : List[str] ,A_ : Union[str, Any]=False ) -> str: with torch.no_grad(): A = MaskaFormerModel(config=A_ ) model.to(A_ ) model.eval() A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ,output_hidden_states=A_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : Any ,A_ : Dict ,A_ : Any ,A_ : Dict ) -> Optional[Any]: A = MaskaFormerForUniversalSegmentation(config=A_ ) model.to(A_ ) model.eval() def comm_check_on_output(A_ : str ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A = model(pixel_values=A_ ,pixel_mask=A_ ) A = model(A_ ) comm_check_on_output(A_ ) A = model( pixel_values=A_ ,pixel_mask=A_ ,mask_labels=A_ ,class_labels=A_ ) comm_check_on_output(A_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCamelCase: Optional[Any] = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} _lowerCamelCase: int = False _lowerCamelCase: Dict = False _lowerCamelCase: List[str] = False _lowerCamelCase: int = False def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = MaskaFormerModelTester(self ) A = ConfigTester(self ,config_class=A_ ,has_text_modality=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) A = inspect.signature(model.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_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A = MaskaFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = (self.model_tester.min_size,) * 2 A = { 'pixel_values': torch.randn((2, 3, *size) ,device=A_ ), 'mask_labels': torch.randn((2, 10, *size) ,device=A_ ), 'class_labels': torch.zeros(2 ,10 ,device=A_ ).long(), } A = self.model_tester.get_config() A = MaskaFormerForUniversalSegmentation(A_ ).to(A_ ) A = model(**A_ ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: A , A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(A_ ,**A_ ,output_hidden_states=A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ).to(A_ ) A = model(**A_ ,output_attentions=A_ ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: if not self.model_tester.is_training: return A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = model_class(A_ ) model.to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.all_model_classes[1] A , A , A , A , A = self.model_tester.prepare_config_and_inputs() A = True A = True A = model_class(A_ ).to(A_ ) model.train() A = model(A_ ,mask_labels=A_ ,class_labels=A_ ) A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=A_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowercase = 1e-4 def _snake_case ( ): A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(A_ ) A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) A = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,A_ ,atol=A_ ) ) A = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(A_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = prepare_img() A = image_processor(A_ ,return_tensors='pt' ).to(A_ ) A = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(A_ ,(1, 3, 384, 384) ) with torch.no_grad(): A = model(**A_ ) # masks_queries_logits A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] A = torch.tensor(A_ ).to(A_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,A_ ,atol=A_ ) ) # class_queries_logits A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(A_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,A_ ,atol=A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(A_ ).eval() A = self.default_image_processor A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors='pt' ,) A = inputs['pixel_values'].to(A_ ) A = [el.to(A_ ) for el in inputs['mask_labels']] A = [el.to(A_ ) for el in inputs['class_labels']] with torch.no_grad(): A = model(**A_ ) self.assertTrue(outputs.loss is not None )
22
1
"""simple docstring""" def _snake_case ( snake_case__ : int ): if num <= 0: raise ValueError('Input must be a positive integer' ) A = [True] * (num + 1) A = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , snake_case__ ): A = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() _lowercase = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
22
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ,A_ : Optional[Any] ,) -> Optional[int]: A = parent A = 13 A = 7 A = True A = True A = True A = 99 A = 32 A = 2 A = 4 A = 37 A = 'gelu' A = 0.1 A = 0.1 A = 512 A = 16 A = 2 A = 0.02 A = 3 A = 4 A = None def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,self.num_choices ) A = EsmConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,pad_token_id=1 ,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 ,) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[Any] ,A_ : Any ,A_ : Any ) -> Dict: A = TFEsmModel(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,) -> Optional[int]: A = True A = TFEsmModel(config=A_ ) A = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } A = model(A_ ) A = [input_ids, input_mask] A = model(A_ ,encoder_hidden_states=A_ ) # Also check the case where encoder outputs are not passed A = model(A_ ,attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : List[Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ) -> Dict: A = TFEsmForMaskedLM(config=A_ ) A = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Optional[int] ) -> Union[str, Any]: A = self.num_labels A = TFEsmForTokenClassification(config=A_ ) A = {'input_ids': input_ids, 'attention_mask': input_mask} A = model(A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _lowerCamelCase: List[str] = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) _lowerCamelCase: Union[str, Any] = False _lowerCamelCase: List[Any] = False def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: A = TFEsmModelTester(self ) A = ConfigTester(self ,config_class=A_ ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = TFEsmModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: pass @unittest.skip('Protein models do not support embedding resizing.' ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: pass def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(A_ ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer A = model.get_bias() assert isinstance(A_ ,A_ ) for k, v in name.items(): assert isinstance(A_ ,tf.Variable ) else: A = model.get_output_embeddings() assert x is None A = model.get_bias() assert name is None @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 1, 2, 3, 4, 5]] ) A = model(A_ )[0] A = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) ,A_ ) # compare the actual values for a slice. A = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-2 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: A = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) A = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) A = model(A_ )[0] # compare the actual values for a slice. A = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
22
1
"""simple docstring""" import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available _lowercase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: List[str] _lowerCamelCase: Optional[List[str]] @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: List[int] _lowerCamelCase: List[int] _lowerCamelCase: Optional[List[int]] = None _lowerCamelCase: Optional[List[int]] = None class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = '''train''' _lowerCamelCase: Tuple = '''dev''' _lowerCamelCase: Optional[Any] = '''test''' class lowerCAmelCase_ : '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[str] ,A_ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : str ) -> List[str]: raise NotImplementedError @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : List[InputExample] ,A_ : List[str] ,A_ : int ,A_ : PreTrainedTokenizer ,A_ : int=False ,A_ : Optional[int]="[CLS]" ,A_ : Union[str, Any]=1 ,A_ : Union[str, Any]="[SEP]" ,A_ : int=False ,A_ : List[Any]=False ,A_ : Any=0 ,A_ : List[str]=0 ,A_ : int=-100 ,A_ : List[str]=0 ,A_ : Tuple=True ,) -> List[InputFeatures]: A = {label: i for i, label in enumerate(A_ )} A = [] for ex_index, example in enumerate(A_ ): if ex_index % 1_0000 == 0: logger.info('Writing example %d of %d' ,A_ ,len(A_ ) ) A = [] A = [] for word, label in zip(example.words ,example.labels ): A = tokenizer.tokenize(A_ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(A_ ) > 0: tokens.extend(A_ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(A_ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. A = tokenizer.num_special_tokens_to_add() if len(A_ ) > max_seq_length - special_tokens_count: A = tokens[: (max_seq_length - special_tokens_count)] A = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] A = [sequence_a_segment_id] * len(A_ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: A = [cls_token] + tokens A = [pad_token_label_id] + label_ids A = [cls_token_segment_id] + segment_ids A = tokenizer.convert_tokens_to_ids(A_ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. A = [1 if mask_padding_with_zero else 0] * len(A_ ) # Zero-pad up to the sequence length. A = max_seq_length - len(A_ ) if pad_on_left: A = ([pad_token] * padding_length) + input_ids A = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask A = ([pad_token_segment_id] * padding_length) + segment_ids A = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length if ex_index < 5: logger.info('*** Example ***' ) logger.info('guid: %s' ,example.guid ) logger.info('tokens: %s' ,' '.join([str(A_ ) for x in tokens] ) ) logger.info('input_ids: %s' ,' '.join([str(A_ ) for x in input_ids] ) ) logger.info('input_mask: %s' ,' '.join([str(A_ ) for x in input_mask] ) ) logger.info('segment_ids: %s' ,' '.join([str(A_ ) for x in segment_ids] ) ) logger.info('label_ids: %s' ,' '.join([str(A_ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: A = None features.append( InputFeatures( input_ids=A_ ,attention_mask=A_ ,token_type_ids=A_ ,label_ids=A_ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[InputFeatures] _lowerCamelCase: int = nn.CrossEntropyLoss().ignore_index def __init__( self : Tuple ,A_ : TokenClassificationTask ,A_ : str ,A_ : PreTrainedTokenizer ,A_ : List[str] ,A_ : str ,A_ : Optional[int] = None ,A_ : Optional[int]=False ,A_ : Split = Split.train ,) -> Dict: # Load data features from cache or dataset file A = os.path.join( A_ ,'cached_{}_{}_{}'.format(mode.value ,tokenizer.__class__.__name__ ,str(A_ ) ) ,) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. A = cached_features_file + '.lock' with FileLock(A_ ): if os.path.exists(A_ ) and not overwrite_cache: logger.info(F'Loading features from cached file {cached_features_file}' ) A = torch.load(A_ ) else: logger.info(F'Creating features from dataset file at {data_dir}' ) A = token_classification_task.read_examples_from_file(A_ ,A_ ) # TODO clean up all this to leverage built-in features of tokenizers A = token_classification_task.convert_examples_to_features( A_ ,A_ ,A_ ,A_ ,cls_token_at_end=bool(model_type in ['xlnet'] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ['xlnet'] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=A_ ,pad_on_left=bool(tokenizer.padding_side == 'left' ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) logger.info(F'Saving features into cached file {cached_features_file}' ) torch.save(self.features ,A_ ) def __len__( self : Optional[int] ) -> List[str]: return len(self.features ) def __getitem__( self : List[Any] ,A_ : Optional[int] ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: List[InputFeatures] _lowerCamelCase: int = -100 def __init__( self : Any ,A_ : TokenClassificationTask ,A_ : str ,A_ : PreTrainedTokenizer ,A_ : List[str] ,A_ : str ,A_ : Optional[int] = None ,A_ : str=False ,A_ : Split = Split.train ,) -> Tuple: A = token_classification_task.read_examples_from_file(A_ ,A_ ) # TODO clean up all this to leverage built-in features of tokenizers A = token_classification_task.convert_examples_to_features( A_ ,A_ ,A_ ,A_ ,cls_token_at_end=bool(model_type in ['xlnet'] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ['xlnet'] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=A_ ,pad_on_left=bool(tokenizer.padding_side == 'left' ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: A = tf.data.Dataset.from_generator( A_ ,({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa) ,( {'input_ids': tf.TensorShape([None] ), 'attention_mask': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) ,) else: A = tf.data.Dataset.from_generator( A_ ,({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa) ,( { 'input_ids': tf.TensorShape([None] ), 'attention_mask': tf.TensorShape([None] ), 'token_type_ids': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) ,) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : Optional[Any] ) -> str: return len(self.features ) def __getitem__( self : Union[str, Any] ,A_ : Optional[Any] ) -> InputFeatures: return self.features[i]
22
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys _lowercase = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') _lowercase = subprocess.check_output(F"""git diff --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() _lowercase = '''|'''.join(sys.argv[1:]) _lowercase = re.compile(rF"""^({joined_dirs}).*?\.py$""") _lowercase = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
22
1
"""simple docstring""" def _snake_case ( snake_case__ : list[int] , snake_case__ : list[int] ): A = len(snake_case__ ) print('The following activities are selected:' ) # The first activity is always selected A = 0 print(snake_case__ , end=',' ) # Consider rest of the activities for j in range(snake_case__ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(snake_case__ , end=',' ) A = j if __name__ == "__main__": import doctest doctest.testmod() _lowercase = [1, 3, 0, 5, 8, 5] _lowercase = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
22
"""simple docstring""" import sys from collections import defaultdict class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ) -> int: A = [] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ) -> Optional[int]: return self.node_position[vertex] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ,A_ : Any ) -> List[Any]: A = pos def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : str ,A_ : Dict ,A_ : List[str] ) -> str: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: A = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: A = 2 * start + 1 else: A = 2 * start + 2 if heap[smallest_child] < heap[start]: A , A = heap[smallest_child], positions[smallest_child] A , A = ( heap[start], positions[start], ) A , A = temp, tempa A = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] ,self.get_position(positions[start] ) ) self.set_position(positions[start] ,A_ ) self.top_to_bottom(A_ ,A_ ,A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Optional[int] ,A_ : Dict ,A_ : str ,A_ : Union[str, Any] ) -> Dict: A = position[index] while index != 0: A = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: A = heap[parent] A = position[parent] self.set_position(position[parent] ,A_ ) else: A = val A = temp self.set_position(A_ ,A_ ) break A = parent else: A = val A = temp self.set_position(A_ ,0 ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple ,A_ : Dict ) -> Union[str, Any]: A = len(A_ ) // 2 - 1 for i in range(A_ ,-1 ,-1 ): self.top_to_bottom(A_ ,A_ ,len(A_ ) ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int] ,A_ : Dict ) -> Union[str, Any]: A = positions[0] A = sys.maxsize self.top_to_bottom(A_ ,0 ,len(A_ ) ,A_ ) return temp def _snake_case ( snake_case__ : Dict ): A = Heap() A = [0] * len(snake_case__ ) A = [-1] * len(snake_case__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph A = [] # Heap of Distance of vertices from their neighboring vertex A = [] for vertex in range(len(snake_case__ ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case__ ) heap.node_position.append(snake_case__ ) A = [] A = 1 A = sys.maxsize for neighbor, distance in adjacency_list[0]: A = 0 A = distance heap.heapify(snake_case__ , snake_case__ ) for _ in range(1 , len(snake_case__ ) ): A = heap.delete_minimum(snake_case__ , snake_case__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) A = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case__ )] ): A = distance heap.bottom_to_top( snake_case__ , heap.get_position(snake_case__ ) , snake_case__ , snake_case__ ) A = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > _lowercase = int(input('''Enter number of edges: ''').strip()) _lowercase = defaultdict(list) for _ in range(edges_number): _lowercase = [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))
22
1
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: int class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : int ) -> Optional[Any]: A = [[] for _ in range(A_ )] A = size def __getitem__( self : Optional[int] ,A_ : int ) -> Iterator[Edge]: return iter(self._graph[vertex] ) @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self._size def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int ,A_ : int ,A_ : int ) -> str: if weight not in (0, 1): raise ValueError('Edge weight must be either 0 or 1.' ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError('Vertex indexes must be in [0; size).' ) self._graph[from_vertex].append(Edge(A_ ,A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : int ,A_ : int ) -> int | None: A = deque([start_vertex] ) A = [None] * self.size A = 0 while queue: A = queue.popleft() A = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: A = current_distance + edge.weight A = distances[edge.destination_vertex] if ( isinstance(A_ ,A_ ) and new_distance >= dest_vertex_distance ): continue A = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError('No path from start_vertex to finish_vertex.' ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
22
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter _lowercase = True except ImportError: _lowercase = False _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( snake_case__ : Namespace ): return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' ,action='store_true' ,help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' ,type=A_ ,help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' ,type=A_ ,help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=A_ ) def __init__( self : Tuple ,A_ : bool ,A_ : str ,A_ : Tuple=None ,*A_ : List[str] ) -> Union[str, Any]: A = testing A = testing_file A = path def _SCREAMING_SNAKE_CASE ( self : int ) -> int: warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory A = [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(A_ ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) A = ( Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) A = path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(A_ ) ) else: with open(self._testing_file ,'r' ) as configuration_file: A = json.load(A_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) ,no_input=A_ ,extra_context=A_ ,) A = [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' ,'r' ) as configuration_file: A = json.load(A_ ) A = configuration['lowercase_modelname'] A = configuration['generate_tensorflow_pytorch_and_flax'] os.remove(F'{directory}/configuration.json' ) A = 'PyTorch' in generate_tensorflow_pytorch_and_flax A = 'TensorFlow' in generate_tensorflow_pytorch_and_flax A = 'Flax' in generate_tensorflow_pytorch_and_flax A = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}' os.makedirs(A_ ,exist_ok=A_ ) os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' ,exist_ok=A_ ) # Tests require submodules as they have parent imports with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' ,'w' ): pass shutil.move( F'{directory}/__init__.py' ,F'{model_dir}/__init__.py' ,) shutil.move( F'{directory}/configuration_{lowercase_model_name}.py' ,F'{model_dir}/configuration_{lowercase_model_name}.py' ,) def remove_copy_lines(A_ : int ): with open(A_ ,'r' ) as f: A = f.readlines() with open(A_ ,'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(A_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_{lowercase_model_name}.py' ,F'{model_dir}/modeling_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_tf_{lowercase_model_name}.py' ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' ) if output_flax: if not self._testing: remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/modeling_flax_{lowercase_model_name}.py' ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' ,) else: os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' ) os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' ) shutil.move( F'{directory}/{lowercase_model_name}.md' ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' ,) shutil.move( F'{directory}/tokenization_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}.py' ,) shutil.move( F'{directory}/tokenization_fast_{lowercase_model_name}.py' ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' ,) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(A_ : str ,A_ : str ,A_ : List[str] ): # Create temp file A , A = mkstemp() A = False with fdopen(A_ ,'w' ) as new_file: with open(A_ ) as old_file: for line in old_file: new_file.write(A_ ) if line_to_copy_below in line: A = True for line_to_copy in lines_to_copy: new_file.write(A_ ) if not line_found: raise ValueError(F'Line {line_to_copy_below} was not found in file.' ) # Copy the file permissions from the old file to the new file copymode(A_ ,A_ ) # Remove original file remove(A_ ) # Move new file move(A_ ,A_ ) def skip_units(A_ : Dict ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(A_ : Tuple ): with open(A_ ) as datafile: A = [] A = False A = False for line in datafile: if "# To replace in: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# Below: " in line and "##" not in line: A = line.split('"' )[1] A = skip_units(A_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(A_ ,A_ ,A_ ) A = [] elif "# Replace with" in line and "##" not in line: A = [] elif "##" not in line: lines_to_copy.append(A_ ) remove(A_ ) replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' ) os.rmdir(A_ )
22
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Tuple ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : List[Any] , snake_case__ : Union[str, Any] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
22
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : int ,A_ : Tuple ,A_ : str=7 ,A_ : Tuple=3 ,A_ : List[Any]=18 ,A_ : List[str]=30 ,A_ : Optional[Any]=400 ,A_ : Any=True ,A_ : Optional[Any]=None ,A_ : List[str]=True ,) -> str: A = size if size is not None else {'height': 18, 'width': 18} A = parent A = batch_size A = num_channels A = image_size A = min_resolution A = max_resolution A = do_resize A = size A = do_normalize def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04], [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: A = ImageGPTImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ ,'clusters' ) ) self.assertTrue(hasattr(A_ ,'do_resize' ) ) self.assertTrue(hasattr(A_ ,'size' ) ) self.assertTrue(hasattr(A_ ,'do_normalize' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'height': 18, 'width': 18} ) A = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'height': 42, 'width': 42} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: A = self.image_processing_class(**self.image_processor_dict ) A = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,obj[key] ) ) else: self.assertEqual(obj[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(A_ ,'image_processor.json' ) image_processor_first.to_json_file(A_ ) A = self.image_processing_class.from_json_file(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: A = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(A_ ) A = self.image_processing_class.from_pretrained(A_ ).to_dict() A = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(A_ ,image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] ,A_ ) @unittest.skip('ImageGPT requires clusters at initialization' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: pass def _snake_case ( ): A = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) A = Image.open(dataset[4]['file'] ) A = Image.open(dataset[5]['file'] ) A = [imagea, imagea] return images @require_vision @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : str ) -> int: A = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) A = prepare_images() # test non-batched A = image_processing(images[0] ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(1, 1024) ) A = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() ,A_ ) # test batched A = image_processing(A_ ,return_tensors='pt' ) self.assertIsInstance(encoding.input_ids ,torch.LongTensor ) self.assertEqual(encoding.input_ids.shape ,(2, 1024) ) A = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() ,A_ )
22
1
"""simple docstring""" import random def _snake_case ( snake_case__ : List[Any] , snake_case__ : str , snake_case__ : List[str] ): A = a[left_index] A = left_index + 1 for j in range(left_index + 1 , snake_case__ ): if a[j] < pivot: A , A = a[i], a[j] i += 1 A , A = a[i - 1], a[left_index] return i - 1 def _snake_case ( snake_case__ : Dict , snake_case__ : Union[str, Any] , snake_case__ : str ): if left < right: A = random.randint(snake_case__ , right - 1 ) A , A = ( a[left], a[pivot], ) # switches the pivot with the left most bound A = partition(snake_case__ , snake_case__ , snake_case__ ) quick_sort_random( snake_case__ , snake_case__ , snake_case__ ) # recursive quicksort to the left of the pivot point quick_sort_random( snake_case__ , pivot_index + 1 , snake_case__ ) # recursive quicksort to the right of the pivot point def _snake_case ( ): A = input('Enter numbers separated by a comma:\n' ).strip() A = [int(snake_case__ ) for item in user_input.split(',' )] quick_sort_random(snake_case__ , 0 , len(snake_case__ ) ) print(snake_case__ ) if __name__ == "__main__": main()
22
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def _snake_case ( snake_case__ : Optional[int] ): return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ) -> Any: A = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' ,type=A_ ,default=A_ ,help='Path to location to store the models' ) download_parser.add_argument( '--force' ,action='store_true' ,help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' ,action='store_true' ,help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' ,) download_parser.add_argument('model' ,type=A_ ,help='Name of the model to download' ) download_parser.set_defaults(func=A_ ) def __init__( self : Dict ,A_ : str ,A_ : str ,A_ : bool ,A_ : bool ) -> Union[str, Any]: A = model A = cache A = force A = trust_remote_code def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model ,cache_dir=self._cache ,force_download=self._force ,trust_remote_code=self._trust_remote_code )
22
1
"""simple docstring""" import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: float = 0.0 _lowerCamelCase: int = 1 _lowerCamelCase: int = 1 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = False _lowerCamelCase: bool = False _lowerCamelCase: jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : int ) -> Any: A = [] A = [] for i in range(self.num_layers ): A = self.in_channels if i == 0 else self.out_channels A = FlaxResnetBlockaD( in_channels=A_ ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(A_ ) A = FlaxTransformeraDModel( in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(A_ ) A = resnets A = attentions if self.add_downsample: A = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : int ,A_ : Optional[int] ,A_ : Any ,A_ : int ,A_ : Dict=True ) -> str: A = () for resnet, attn in zip(self.resnets ,self.attentions ): A = resnet(A_ ,A_ ,deterministic=A_ ) A = attn(A_ ,A_ ,deterministic=A_ ) output_states += (hidden_states,) if self.add_downsample: A = self.downsamplers_a(A_ ) output_states += (hidden_states,) return hidden_states, output_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: float = 0.0 _lowerCamelCase: int = 1 _lowerCamelCase: bool = True _lowerCamelCase: jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: A = [] for i in range(self.num_layers ): A = self.in_channels if i == 0 else self.out_channels A = FlaxResnetBlockaD( in_channels=A_ ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(A_ ) A = resnets if self.add_downsample: A = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : str ,A_ : Any ,A_ : Tuple ,A_ : List[str]=True ) -> List[str]: A = () for resnet in self.resnets: A = resnet(A_ ,A_ ,deterministic=A_ ) output_states += (hidden_states,) if self.add_downsample: A = self.downsamplers_a(A_ ) output_states += (hidden_states,) return hidden_states, output_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: float = 0.0 _lowerCamelCase: int = 1 _lowerCamelCase: int = 1 _lowerCamelCase: bool = True _lowerCamelCase: bool = False _lowerCamelCase: bool = False _lowerCamelCase: bool = False _lowerCamelCase: jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: A = [] A = [] for i in range(self.num_layers ): A = self.in_channels if (i == self.num_layers - 1) else self.out_channels A = self.prev_output_channel if i == 0 else self.out_channels A = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(A_ ) A = FlaxTransformeraDModel( in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(A_ ) A = resnets A = attentions if self.add_upsample: A = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : List[str] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str=True ) -> int: for resnet, attn in zip(self.resnets ,self.attentions ): # pop res hidden states A = res_hidden_states_tuple[-1] A = res_hidden_states_tuple[:-1] A = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 ) A = resnet(A_ ,A_ ,deterministic=A_ ) A = attn(A_ ,A_ ,deterministic=A_ ) if self.add_upsample: A = self.upsamplers_a(A_ ) return hidden_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: int _lowerCamelCase: float = 0.0 _lowerCamelCase: int = 1 _lowerCamelCase: bool = True _lowerCamelCase: jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = [] for i in range(self.num_layers ): A = self.in_channels if (i == self.num_layers - 1) else self.out_channels A = self.prev_output_channel if i == 0 else self.out_channels A = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(A_ ) A = resnets if self.add_upsample: A = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype ) def __call__( self : Union[str, Any] ,A_ : Tuple ,A_ : Any ,A_ : Optional[int] ,A_ : int=True ) -> List[str]: for resnet in self.resnets: # pop res hidden states A = res_hidden_states_tuple[-1] A = res_hidden_states_tuple[:-1] A = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 ) A = resnet(A_ ,A_ ,deterministic=A_ ) if self.add_upsample: A = self.upsamplers_a(A_ ) return hidden_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' _lowerCamelCase: int _lowerCamelCase: float = 0.0 _lowerCamelCase: int = 1 _lowerCamelCase: int = 1 _lowerCamelCase: bool = False _lowerCamelCase: bool = False _lowerCamelCase: jnp.dtype = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: # there is always at least one resnet A = [ FlaxResnetBlockaD( in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) ] A = [] for _ in range(self.num_layers ): A = FlaxTransformeraDModel( in_channels=self.in_channels ,n_heads=self.num_attention_heads ,d_head=self.in_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,) attentions.append(A_ ) A = FlaxResnetBlockaD( in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,) resnets.append(A_ ) A = resnets A = attentions def __call__( self : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : List[str]=True ) -> Tuple: A = self.resnets[0](A_ ,A_ ) for attn, resnet in zip(self.attentions ,self.resnets[1:] ): A = attn(A_ ,A_ ,deterministic=A_ ) A = resnet(A_ ,A_ ,deterministic=A_ ) return hidden_states
22
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = {'''vocab_file''': '''spm_char.model'''} _lowercase = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } _lowercase = { '''microsoft/speecht5_asr''': 10_24, '''microsoft/speecht5_tts''': 10_24, '''microsoft/speecht5_vc''': 10_24, } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None: A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Any: A = self.__dict__.copy() A = None return state def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]: return self.sp_model.piece_to_id(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]: A = self.sp_model.IdToPiece(A_ ) return token def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]: A = [] A = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ ) A = [1] if token_ids_a is None: return ([0] * len(A_ )) + suffix_ones return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
22
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : List[str] , snake_case__ : int=False , snake_case__ : Dict=False , snake_case__ : Union[str, Any]=False ): A = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'transformer.blocks.{i}.norm1.weight', F'vilt.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm1.bias', F'vilt.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.weight', F'vilt.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.bias', F'vilt.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.norm2.weight', F'vilt.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm2.bias', F'vilt.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (F'transformer.blocks.{i}.mlp.fc1.weight', F'vilt.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc1.bias', F'vilt.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.weight', F'vilt.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.bias', F'vilt.encoder.layer.{i}.output.dense.bias') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _snake_case ( snake_case__ : Dict , snake_case__ : Any ): for i in range(config.num_hidden_layers ): A = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A = state_dict.pop(F'transformer.blocks.{i}.attn.qkv.weight' ) A = state_dict.pop(F'transformer.blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A = in_proj_weight[ : config.hidden_size, : ] A = in_proj_bias[: config.hidden_size] A = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A = in_proj_weight[ -config.hidden_size :, : ] A = in_proj_bias[-config.hidden_size :] def _snake_case ( snake_case__ : Optional[Any] ): A = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[Any] , snake_case__ : str ): A = dct.pop(snake_case__ ) A = val @torch.no_grad() def _snake_case ( snake_case__ : str , snake_case__ : List[Any] ): A = ViltConfig(image_size=384 , patch_size=32 , tie_word_embeddings=snake_case__ ) A = False A = False A = False A = False if "vqa" in checkpoint_url: A = True A = 3129 A = 'huggingface/label-files' A = 'vqa2-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = ViltForQuestionAnswering(snake_case__ ) elif "nlvr" in checkpoint_url: A = True A = 2 A = {0: 'False', 1: 'True'} A = {v: k for k, v in config.idalabel.items()} A = 3 A = ViltForImagesAndTextClassification(snake_case__ ) elif "irtr" in checkpoint_url: A = True A = ViltForImageAndTextRetrieval(snake_case__ ) elif "mlm_itm" in checkpoint_url: A = True A = ViltForMaskedLM(snake_case__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys A = torch.hub.load_state_dict_from_url(snake_case__ , map_location='cpu' )['state_dict'] A = create_rename_keys(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , snake_case__ ) if mlm_model or irtr_model: A = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) # load state dict into HuggingFace model model.eval() if mlm_model: A , A = model.load_state_dict(snake_case__ , strict=snake_case__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(snake_case__ ) # Define processor A = ViltImageProcessor(size=384 ) A = BertTokenizer.from_pretrained('bert-base-uncased' ) A = ViltProcessor(snake_case__ , snake_case__ ) # Forward pass on example inputs (image + text) if nlvr_model: A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=snake_case__ ).raw ) A = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=snake_case__ ).raw ) A = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) A = processor(snake_case__ , snake_case__ , return_tensors='pt' ) A = processor(snake_case__ , snake_case__ , return_tensors='pt' ) A = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: A = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=snake_case__ ).raw ) if mlm_model: A = 'a bunch of [MASK] laying on a [MASK].' else: A = 'How many cats are there?' A = processor(snake_case__ , snake_case__ , return_tensors='pt' ) A = model(**snake_case__ ) # Verify outputs if mlm_model: A = torch.Size([1, 11, 3_0522] ) A = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , snake_case__ , atol=1e-4 ) # verify masked token prediction equals "cats" A = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: A = torch.Size([1, 3129] ) A = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , snake_case__ , atol=1e-4 ) # verify vqa prediction equals "2" A = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: A = torch.Size([1, 2] ) A = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4 ) assert outputs.logits.shape == expected_shape Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F'Saving model and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) processor.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''', type=str, help='''URL of the checkpoint 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 = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''CLIPFeatureExtractor'''] _lowercase = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _lowercase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: Optional[str] = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''The column name of the images in the files.'''} ) _lowerCamelCase: Optional[str] = field(default=_lowercase , metadata={'''help''': '''A folder containing the training data.'''} ) _lowerCamelCase: Optional[str] = field(default=_lowercase , metadata={'''help''': '''A folder containing the validation data.'''} ) _lowerCamelCase: Optional[float] = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) _lowerCamelCase: Optional[int] = field( default=_lowercase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) _lowerCamelCase: Optional[int] = field( default=_lowercase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = {} if self.train_dir is not None: A = self.train_dir if self.validation_dir is not None: A = self.validation_dir A = data_files if data_files else None @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str = field( default=_lowercase , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) _lowerCamelCase: Optional[str] = field( default=_lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) _lowerCamelCase: str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) _lowerCamelCase: str = field(default=_lowercase , metadata={'''help''': '''Name or path of preprocessor config.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) _lowerCamelCase: float = field( default=0.75 , metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: float = field( default=1E-3 , metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( snake_case__ : Union[str, Any] ): A = torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. A = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A , A , A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A , A , A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , snake_case__ , snake_case__ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A = training_args.get_process_log_level() logger.setLevel(snake_case__ ) transformers.utils.logging.set_verbosity(snake_case__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. A = None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case__ ) and data_args.train_val_split > 0.0: A = ds['train'].train_test_split(data_args.train_val_split ) A = split['train'] A = split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: A = ViTMAEConfig.from_pretrained(model_args.config_name , **snake_case__ ) elif model_args.model_name_or_path: A = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **snake_case__ ) else: A = ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: A = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **snake_case__ ) elif model_args.model_name_or_path: A = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **snake_case__ ) else: A = ViTImageProcessor() # create model if model_args.model_name_or_path: A = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=snake_case__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) A = ViTMAEForPreTraining(snake_case__ ) if training_args.do_train: A = ds['train'].column_names else: A = ds['validation'].column_names if data_args.image_column_name is not None: A = data_args.image_column_name elif "image" in column_names: A = 'image' elif "img" in column_names: A = 'img' else: A = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: A = image_processor.size['shortest_edge'] else: A = (image_processor.size['height'], image_processor.size['width']) A = Compose( [ Lambda(lambda snake_case__ : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(snake_case__ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(snake_case__ : Dict ): A = [transforms(snake_case__ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: A = ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: A = ( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case__ ) # Compute absolute learning rate A = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: A = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer A = Trainer( model=snake_case__ , args=snake_case__ , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=snake_case__ , data_collator=snake_case__ , ) # Training if training_args.do_train: A = None if training_args.resume_from_checkpoint is not None: A = training_args.resume_from_checkpoint elif last_checkpoint is not None: A = last_checkpoint A = trainer.train(resume_from_checkpoint=snake_case__ ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A = trainer.evaluate() trainer.log_metrics('eval' , snake_case__ ) trainer.save_metrics('eval' , snake_case__ ) # Write model card and (optionally) push to hub A = { 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case__ ) else: trainer.create_model_card(**snake_case__ ) def _snake_case ( snake_case__ : Optional[int] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
22
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any ,A_ : Optional[Any] ,A_ : Tuple=13 ,A_ : Optional[Any]=7 ,A_ : Dict=True ,A_ : Optional[Any]=True ,A_ : str=True ,A_ : Union[str, Any]=True ,A_ : Optional[Any]=True ,A_ : Tuple=False ,A_ : Optional[int]=False ,A_ : str=False ,A_ : int=2 ,A_ : Union[str, Any]=99 ,A_ : int=0 ,A_ : Dict=32 ,A_ : List[str]=5 ,A_ : Any=4 ,A_ : str=0.1 ,A_ : Any=0.1 ,A_ : int=512 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.02 ,A_ : Optional[Any]=2 ,A_ : List[str]=4 ,A_ : Optional[int]="last" ,A_ : str=True ,A_ : List[str]=None ,A_ : List[Any]=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Any ,A_ : List[str] ,A_ : Optional[int] ,) -> Tuple: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ,A_ : Any ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : List[str] ,A_ : List[str] ,) -> Union[str, Any]: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ,A_ : Tuple ,A_ : str ,A_ : int ,A_ : str ,A_ : Optional[Any] ,A_ : Any ,A_ : Any ,A_ : Dict ,) -> List[str]: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Dict ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : List[str] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : str ,A_ : Any ,) -> Optional[int]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Union[str, Any] ,A_ : Tuple ,A_ : int ,A_ : Union[str, Any] ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : str ,) -> List[Any]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any] ,A_ : str ,A_ : Tuple ,A_ : List[str] ,A_ : Dict ,A_ : Dict ,A_ : Union[str, Any] ,A_ : Dict ,A_ : Any ,) -> Any: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : str ,A_ : int ,A_ : Tuple ,A_ : List[Any] ,A_ : List[str] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : int ,) -> Tuple: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: Dict = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[Any] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Any ,A_ : str ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[int] ,A_ : Tuple ,A_ : str=False ) -> Dict: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Dict ,A_ : List[Any] ,A_ : List[Any] ,A_ : Dict ,A_ : Union[str, Any] ,A_ : List[Any]=False ,A_ : Tuple=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Dict ,A_ : Optional[Any] ,A_ : Dict ,A_ : Tuple=False ,A_ : Optional[Any]=1 ) -> List[str]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
22
1
"""simple docstring""" import argparse import copy def _snake_case ( snake_case__ : List[Any] ): A = {} with open(snake_case__ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: A = [] _list.append([line.split()[1], line.split()[2]] ) A = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: A = [] _list.append([line.split()[0], line.split()[2]] ) A = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def _snake_case ( snake_case__ : str , snake_case__ : Any ): with open(snake_case__ ) as f: A = f.read(1 ) A = start_node A = [] A = start_node A = 0 while visiting not in first_solution: A = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(snake_case__ ) and k[0] not in first_solution: A = k[1] A = k[0] first_solution.append(snake_case__ ) A = distance_of_first_solution + int(snake_case__ ) A = best_node first_solution.append(snake_case__ ) A = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 A = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = [] for n in solution[1:-1]: A = solution.index(snake_case__ ) for kn in solution[1:-1]: A = solution.index(snake_case__ ) if n == kn: continue A = copy.deepcopy(snake_case__ ) A = kn A = n A = 0 for k in _tmp[:-1]: A = _tmp[_tmp.index(snake_case__ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: A = distance + int(i[1] ) _tmp.append(snake_case__ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) A = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda snake_case__ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def _snake_case ( snake_case__ : Tuple , snake_case__ : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : Any , snake_case__ : List[str] ): A = 1 A = first_solution A = [] A = distance_of_first_solution A = solution while count <= iters: A = find_neighborhood(snake_case__ , snake_case__ ) A = 0 A = neighborhood[index_of_best_solution] A = len(snake_case__ ) - 1 A = False while not found: A = 0 while i < len(snake_case__ ): if best_solution[i] != solution[i]: A = best_solution[i] A = solution[i] break A = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) A = True A = best_solution[:-1] A = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: A = cost A = solution else: A = index_of_best_solution + 1 A = neighborhood[index_of_best_solution] if len(snake_case__ ) >= size: tabu_list.pop(0 ) A = count + 1 return best_solution_ever, best_cost def _snake_case ( snake_case__ : List[str]=None ): A = generate_neighbours(args.File ) A , A = generate_first_solution( args.File , snake_case__ ) A , A = tabu_search( snake_case__ , snake_case__ , snake_case__ , args.Iterations , args.Size , ) print(F'Best solution: {best_sol}, with total distance: {best_cost}.' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser(description='''Tabu Search''') parser.add_argument( '''-f''', '''--File''', type=str, help='''Path to the file containing the data''', required=True, ) parser.add_argument( '''-i''', '''--Iterations''', type=int, help='''How many iterations the algorithm should perform''', required=True, ) parser.add_argument( '''-s''', '''--Size''', type=int, help='''Size of the tabu list''', required=True ) # Pass the arguments to main method main(parser.parse_args())
22
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowercase = 8 def _snake_case ( snake_case__ : Tuple , snake_case__ : Optional[int]=BITS ): A = x.device A = (x * 255).int().clamp(0 , 255 ) A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b c h w -> b c 1 h w' ) A = ((x & mask) != 0).float() A = rearrange(snake_case__ , 'b c d h w -> b (c d) h w' ) A = bits * 2 - 1 return bits def _snake_case ( snake_case__ : Any , snake_case__ : Any=BITS ): A = x.device A = (x > 0).int() A = 2 ** torch.arange(bits - 1 , -1 , -1 , device=snake_case__ , dtype=torch.intaa ) A = rearrange(snake_case__ , 'd -> d 1 1' ) A = rearrange(snake_case__ , 'b (c d) h w -> b c d h w' , d=8 ) A = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def _snake_case ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : float = 0.0 , snake_case__ : bool = True , snake_case__ : List[str]=None , snake_case__ : bool = True , ): if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A = self.alphas_cumprod[timestep] A = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A = self._get_variance(snake_case__ , snake_case__ ) A = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A = model_output.device if torch.is_tensor(snake_case__ ) else 'cpu' A = torch.randn(model_output.shape , dtype=model_output.dtype , generator=snake_case__ ).to(snake_case__ ) A = self._get_variance(snake_case__ , snake_case__ ) ** 0.5 * eta * noise A = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) def _snake_case ( self : Dict , snake_case__ : torch.FloatTensor , snake_case__ : int , snake_case__ : torch.FloatTensor , snake_case__ : Tuple="epsilon" , snake_case__ : List[str]=None , snake_case__ : bool = True , ): A = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A , A = torch.split(snake_case__ , sample.shape[1] , dim=1 ) else: A = None # 1. compute alphas, betas A = self.alphas_cumprod[t] A = self.alphas_cumprod[t - 1] if t > 0 else self.one A = 1 - alpha_prod_t A = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" A = self.bit_scale if self.config.clip_sample: A = torch.clamp(snake_case__ , -scale , snake_case__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A = 0 if t > 0: A = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=snake_case__ ).to(model_output.device ) A = (self._get_variance(snake_case__ , predicted_variance=snake_case__ ) ** 0.5) * noise A = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=snake_case__ , pred_original_sample=snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : UNetaDConditionModel ,A_ : Union[DDIMScheduler, DDPMScheduler] ,A_ : Optional[float] = 1.0 ,) -> Optional[int]: super().__init__() A = bit_scale A = ( ddim_bit_scheduler_step if isinstance(A_ ,A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ ,scheduler=A_ ) @torch.no_grad() def __call__( self : Tuple ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 256 ,A_ : Optional[int] = 50 ,A_ : Optional[torch.Generator] = None ,A_ : Optional[int] = 1 ,A_ : Optional[str] = "pil" ,A_ : bool = True ,**A_ : Optional[Any] ,) -> Union[Tuple, ImagePipelineOutput]: A = torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=A_ ,) A = decimal_to_bits(A_ ) * self.bit_scale A = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A = self.unet(A_ ,A_ ).sample # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step(A_ ,A_ ,A_ ).prev_sample A = bits_to_decimal(A_ ) if output_type == "pil": A = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
22
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
"""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 _lowercase = logging.get_logger(__name__) _lowercase = { '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''yolos''' def __init__( self : Dict ,A_ : Optional[Any]=768 ,A_ : int=12 ,A_ : List[str]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.0 ,A_ : List[Any]=0.0 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : List[Any]=[512, 864] ,A_ : Union[str, Any]=16 ,A_ : List[str]=3 ,A_ : Optional[int]=True ,A_ : Tuple=100 ,A_ : str=True ,A_ : Optional[Any]=False ,A_ : Any=1 ,A_ : Optional[Any]=5 ,A_ : Optional[Any]=2 ,A_ : Optional[int]=5 ,A_ : List[Any]=2 ,A_ : Union[str, Any]=0.1 ,**A_ : Tuple ,) -> Any: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = num_detection_tokens A = use_mid_position_embeddings A = auxiliary_loss # Hungarian matcher A = class_cost A = bbox_cost A = giou_cost # Loss coefficients A = bbox_loss_coefficient A = giou_loss_coefficient A = eos_coefficient class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Any = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> float: return 1e-4 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return 12
22
1
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def _snake_case ( snake_case__ : int ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Undefined for non-integers' ) elif precision < 1: raise ValueError('Undefined for non-natural numbers' ) A = precision A = ceil(precision / 14 ) A = 42_6880 * Decimal(1_0005 ).sqrt() A = 1 A = 1359_1409 A = Decimal(snake_case__ ) for k in range(1 , snake_case__ ): A = factorial(6 * k ) // (factorial(3 * k ) * factorial(snake_case__ ) ** 3) linear_term += 5_4514_0134 exponential_term *= -26_2537_4126_4076_8000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": _lowercase = 50 print(F"""The first {n} digits of pi is: {pi(n)}""")
22
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=0 ) -> Dict: A = floats_tensor((1, 3, 128, 128) ,rng=random.Random(A_ ) ) A = np.random.RandomState(A_ ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) A = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=A_ ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) # warmup pass to apply optimizations A = pipe(**self.get_dummy_inputs() ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,provider='CPUExecutionProvider' ) A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=A_ ) A = self.get_dummy_inputs() A = pipe(**A_ ).images A = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) A = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = ort.SessionOptions() A = False return options def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) # using the PNDM scheduler by default A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) A = init_image.resize((768, 512) ) A = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,subfolder='scheduler' ,revision='onnx' ) A = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' ,revision='onnx' ,scheduler=A_ ,safety_checker=A_ ,feature_extractor=A_ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=A_ ) A = 'A fantasy landscape, trending on artstation' A = np.random.RandomState(0 ) A = pipe( prompt=A_ ,image=A_ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=A_ ,output_type='np' ,) A = output.images A = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) A = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
22
1
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black _lowercase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowercase = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str ) -> Any: A = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir ,'schedulers/' ) ) A = self.diffusers_dir shutil.copy( os.path.join(A_ ,'src/diffusers/schedulers/scheduling_ddpm.py' ) ,os.path.join(self.diffusers_dir ,'schedulers/scheduling_ddpm.py' ) ,) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'src/diffusers' shutil.rmtree(self.diffusers_dir ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Any ,A_ : Dict ,A_ : int ,A_ : Optional[int]=None ) -> Tuple: A = comment + F'\nclass {class_name}(nn.Module):\n' + class_code if overwrite_result is not None: A = comment + F'\nclass {class_name}(nn.Module):\n' + overwrite_result A = black.Mode(target_versions={black.TargetVersion.PYaa} ,line_length=119 ) A = black.format_str(A_ ,mode=A_ ) A = os.path.join(self.diffusers_dir ,'new_code.py' ) with open(A_ ,'w' ,newline='\n' ) as f: f.write(A_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(A_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name ,overwrite=A_ ) with open(A_ ,'r' ) as f: self.assertTrue(f.read() ,A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: A = check_copies.find_code_in_diffusers('schedulers.scheduling_ddpm.DDPMSchedulerOutput' ) self.assertEqual(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: # Base copy consistency self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' ,'DDPMSchedulerOutput' ,REFERENCE_CODE + '\n' ,) # With no empty line at the end self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' ,'DDPMSchedulerOutput' ,A_ ,) # Copy consistency with rename self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' ,'TestSchedulerOutput' ,re.sub('DDPM' ,'Test' ,A_ ) ,) # Copy consistency with a really long name A = 'TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason' self.check_copy_consistency( F'# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}' ,F'{long_class_name}SchedulerOutput' ,re.sub('Bert' ,A_ ,A_ ) ,) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' ,'TestSchedulerOutput' ,A_ ,overwrite_result=re.sub('DDPM' ,'Test' ,A_ ) ,)
22
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''pixel_values'''] def __init__( self : Optional[Any] ,A_ : bool = True ,A_ : Optional[Dict[str, int]] = None ,A_ : PILImageResampling = PILImageResampling.BILINEAR ,A_ : bool = True ,A_ : Dict[str, int] = None ,A_ : bool = True ,A_ : Union[int, float] = 1 / 255 ,A_ : bool = True ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,**A_ : Optional[Any] ,) -> None: super().__init__(**A_ ) A = size if size is not None else {'shortest_edge': 256} A = get_size_dict(A_ ,default_to_square=A_ ) A = crop_size if crop_size is not None else {'height': 224, 'width': 224} A = get_size_dict(A_ ,param_name='crop_size' ) A = do_resize A = size A = resample A = do_center_crop A = crop_size A = do_rescale A = rescale_factor A = do_normalize A = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : PILImageResampling = PILImageResampling.BICUBIC ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ,default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A = get_resize_output_image_size(A_ ,size=size['shortest_edge'] ,default_to_square=A_ ) return resize(A_ ,size=A_ ,resample=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : Dict[str, int] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : int ,) -> np.ndarray: A = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(A_ ,size=(size['height'], size['width']) ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : np.ndarray ,A_ : float ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : List[str] ) -> np.ndarray: return rescale(A_ ,scale=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : np.ndarray ,A_ : Union[float, List[float]] ,A_ : Union[float, List[float]] ,A_ : Optional[Union[str, ChannelDimension]] = None ,**A_ : Any ,) -> np.ndarray: return normalize(A_ ,mean=A_ ,std=A_ ,data_format=A_ ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : ImageInput ,A_ : Optional[bool] = None ,A_ : Dict[str, int] = None ,A_ : PILImageResampling = None ,A_ : bool = None ,A_ : Dict[str, int] = None ,A_ : Optional[bool] = None ,A_ : Optional[float] = None ,A_ : Optional[bool] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[float, List[float]]] = None ,A_ : Optional[Union[str, TensorType]] = None ,A_ : Union[str, ChannelDimension] = ChannelDimension.FIRST ,**A_ : Tuple ,) -> List[Any]: A = do_resize if do_resize is not None else self.do_resize A = size if size is not None else self.size A = get_size_dict(A_ ,default_to_square=A_ ) A = resample if resample is not None else self.resample A = do_center_crop if do_center_crop is not None else self.do_center_crop A = crop_size if crop_size is not None else self.crop_size A = get_size_dict(A_ ,param_name='crop_size' ) A = do_rescale if do_rescale is not None else self.do_rescale A = rescale_factor if rescale_factor is not None else self.rescale_factor A = do_normalize if do_normalize is not None else self.do_normalize A = image_mean if image_mean is not None else self.image_mean A = image_std if image_std is not None else self.image_std A = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A = [to_numpy_array(A_ ) for image in images] if do_resize: A = [self.resize(image=A_ ,size=A_ ,resample=A_ ) for image in images] if do_center_crop: A = [self.center_crop(image=A_ ,size=A_ ) for image in images] if do_rescale: A = [self.rescale(image=A_ ,scale=A_ ) for image in images] if do_normalize: A = [self.normalize(image=A_ ,mean=A_ ,std=A_ ) for image in images] A = [to_channel_dimension_format(A_ ,A_ ) for image in images] A = {'pixel_values': images} return BatchFeature(data=A_ ,tensor_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any] ,A_ : List[Tuple] = None ) -> str: A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(A_ ): A = target_sizes.numpy() A = [] for idx in range(len(A_ ) ): A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=A_ ) A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: A = logits.argmax(dim=1 ) A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
22
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
"""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 _lowercase = data_utils.TransfoXLTokenizer _lowercase = data_utils.TransfoXLCorpus _lowercase = data_utils _lowercase = data_utils def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : int ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(snake_case__ , 'rb' ) as fp: A = pickle.load(snake_case__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) A = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) A = corpus.vocab.__dict__ torch.save(snake_case__ , snake_case__ ) A = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , snake_case__ ) A = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(snake_case__ , snake_case__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model A = os.path.abspath(snake_case__ ) A = os.path.abspath(snake_case__ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": A = TransfoXLConfig() else: A = TransfoXLConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) A = TransfoXLLMHeadModel(snake_case__ ) A = load_tf_weights_in_transfo_xl(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model A = os.path.join(snake_case__ , snake_case__ ) A = os.path.join(snake_case__ , snake_case__ ) print(F'Save PyTorch model to {os.path.abspath(snake_case__ )}' ) torch.save(model.state_dict() , snake_case__ ) print(F'Save configuration file to {os.path.abspath(snake_case__ )}' ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowercase = 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.''', ) _lowercase = 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, )
22
1
"""simple docstring""" import pytest _lowercase = '''__dummy_dataset1__''' _lowercase = ''' import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) ''' @pytest.fixture def _snake_case ( ): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _snake_case ( ): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _snake_case ( snake_case__ : List[Any] , snake_case__ : Union[str, Any] , snake_case__ : Dict ): A = dataset_loading_script_name A = tmp_path / 'datasets' / script_name script_dir.mkdir(parents=snake_case__ ) A = script_dir / F'{script_name}.py' with open(snake_case__ , 'w' ) as f: f.write(snake_case__ ) return str(snake_case__ )
22
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ) -> int: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any] ,A_ : Any ,A_ : Optional[Any]=1 ) -> int: if self.graph.get(A_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A = [[w, v]] if not self.graph.get(A_ ): A = [] def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Dict ) -> Optional[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int=-2 ,A_ : Dict=-1 ) -> str: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Any=-1 ) -> int: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Union[str, Any]=-2 ) -> Optional[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Tuple ) -> Any: A = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Union[str, Any] ) -> str: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Union[str, Any]=-2 ) -> Any: A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s A = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return sorted_nodes def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Tuple=-2 ,A_ : List[str]=-1 ) -> str: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any]=-2 ) -> Dict: A = time() self.bfs(A_ ) A = time() return end - begin class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: A = {} def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : str ,A_ : List[str]=1 ) -> Dict: # check if the u exists if self.graph.get(A_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A = [[w, v]] # add the other way if self.graph.get(A_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A = [[w, u]] def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[Any] ,A_ : List[str] ) -> List[Any]: if self.graph.get(A_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(A_ ) # the other way round if self.graph.get(A_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : List[str]=-2 ,A_ : List[Any]=-1 ) -> int: if s == d: return [] A = [] A = [] if s == -2: A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(A_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = ss # check if se have reached the starting point if len(A_ ) == 0: return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[int]=-1 ) -> List[Any]: if c == -1: A = floor(random() * 1_0000 ) + 10 for i in range(A_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A = floor(random() * c ) + 1 if n != i: self.add_pair(A_ ,A_ ,1 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict=-2 ) -> List[Any]: A = deque() A = [] if s == -2: A = list(self.graph )[0] d.append(A_ ) visited.append(A_ ) while d: A = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Optional[Any] ) -> List[Any]: return len(self.graph[u] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return list(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: A = [] A = [] A = list(self.graph )[0] stack.append(A_ ) visited.append(A_ ) A = -2 A = [] A = s A = False A = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A = len(A_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A = node[1] break # check if all the children are visited if s == ss: stack.pop() A = True if len(A_ ) != 0: A = stack[len(A_ ) - 1] else: A = False indirect_parents.append(A_ ) A = s A = ss # check if se have reached the starting point if len(A_ ) == 0: return False def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: return list(self.graph ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Optional[Any]=-2 ,A_ : List[str]=-1 ) -> Any: A = time() self.dfs(A_ ,A_ ) A = time() return end - begin def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[Any]=-2 ) -> Union[str, Any]: A = time() self.bfs(A_ ) A = time() return end - begin
22
1
"""simple docstring""" import math import qiskit def _snake_case ( snake_case__ : int = 1 , snake_case__ : int = 1 , snake_case__ : int = 1 ): if ( isinstance(snake_case__ , snake_case__ ) or isinstance(snake_case__ , snake_case__ ) or isinstance(snake_case__ , snake_case__ ) ): raise TypeError('inputs must be integers.' ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError('inputs must be positive.' ) if ( (math.floor(snake_case__ ) != input_a) or (math.floor(snake_case__ ) != input_a) or (math.floor(snake_case__ ) != carry_in) ): raise ValueError('inputs must be exact integers.' ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError('inputs must be less or equal to 2.' ) # build registers A = qiskit.QuantumRegister(4 , 'qr' ) A = qiskit.ClassicalRegister(2 , 'cr' ) # list the entries A = [input_a, input_a, carry_in] A = qiskit.QuantumCircuit(snake_case__ , snake_case__ ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(snake_case__ ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(snake_case__ ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(snake_case__ ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , snake_case__ ) # measure the last two qbits A = qiskit.Aer.get_backend('aer_simulator' ) A = qiskit.execute(snake_case__ , snake_case__ , shots=1000 ) return job.result().get_counts(snake_case__ ) if __name__ == "__main__": print(F"""Total sum count for state is: {quantum_full_adder(1, 1, 1)}""")
22
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _snake_case ( snake_case__ : str = "isbn/0140328726" ): A = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: A = F'{olid} is not a valid Open Library olid' raise ValueError(snake_case__ ) return requests.get(F'https://openlibrary.org/{new_olid}.json' ).json() def _snake_case ( snake_case__ : dict ): A = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} A = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] A = data['First sentence']['value'] for key, value in data.items(): if isinstance(snake_case__ , snake_case__ ): A = ', '.join(snake_case__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowercase = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"""Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.""") continue print(F"""\nSearching Open Library for ISBN: {isbn}...\n""") try: _lowercase = summarize_book(get_openlibrary_data(F"""isbn/{isbn}""")) print('''\n'''.join(F"""{key}: {value}""" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"""Sorry, there are no results for ISBN: {isbn}.""")
22
1
"""simple docstring""" import argparse import collections import os 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_table.py _lowercase = '''src/transformers''' _lowercase = '''docs/source/en''' _lowercase = '''.''' def _snake_case ( snake_case__ : str , snake_case__ : List[Any] , snake_case__ : Dict ): with open(snake_case__ , 'r' , encoding='utf-8' , newline='\n' ) as f: A = f.readlines() # Find the start prompt. A = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _lowercase = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. _lowercase = re.compile(r'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') _lowercase = re.compile(r'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _lowercase = re.compile(r'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. _lowercase = direct_transformers_import(TRANSFORMERS_PATH) def _snake_case ( snake_case__ : Any ): A = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , snake_case__ ) return [m.group(0 ) for m in matches] def _snake_case ( snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] ): A = 2 if text == '✅' or text == '❌' else len(snake_case__ ) A = (width - text_length) // 2 A = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _snake_case ( ): A = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } A = {name: config.replace('Config' , '' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. A = collections.defaultdict(snake_case__ ) A = collections.defaultdict(snake_case__ ) A = collections.defaultdict(snake_case__ ) A = collections.defaultdict(snake_case__ ) A = collections.defaultdict(snake_case__ ) # Let's lookup through all transformers object (once). for attr_name in dir(snake_case__ ): A = None if attr_name.endswith('Tokenizer' ): A = slow_tokenizers A = attr_name[:-9] elif attr_name.endswith('TokenizerFast' ): A = fast_tokenizers A = attr_name[:-13] elif _re_tf_models.match(snake_case__ ) is not None: A = tf_models A = _re_tf_models.match(snake_case__ ).groups()[0] elif _re_flax_models.match(snake_case__ ) is not None: A = flax_models A = _re_flax_models.match(snake_case__ ).groups()[0] elif _re_pt_models.match(snake_case__ ) is not None: A = pt_models A = _re_pt_models.match(snake_case__ ).groups()[0] if lookup_dict is not None: while len(snake_case__ ) > 0: if attr_name in model_name_to_prefix.values(): A = True break # Try again after removing the last word in the name A = ''.join(camel_case_split(snake_case__ )[:-1] ) # Let's build that table! A = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) A = ['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support'] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). A = [len(snake_case__ ) + 2 for c in columns] A = max([len(snake_case__ ) for name in model_names] ) + 2 # Build the table per se A = '|' + '|'.join([_center_text(snake_case__ , snake_case__ ) for c, w in zip(snake_case__ , snake_case__ )] ) + '|\n' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths] ) + "|\n" A = {True: '✅', False: '❌'} for name in model_names: A = model_name_to_prefix[name] A = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(snake_case__ , snake_case__ ) for l, w in zip(snake_case__ , snake_case__ )] ) + "|\n" return table def _snake_case ( snake_case__ : Dict=False ): A , A , A , A = _find_text_in_file( filename=os.path.join(snake_case__ , 'index.md' ) , start_prompt='<!--This table is updated automatically from the auto modules' , end_prompt='<!-- End table-->' , ) A = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(snake_case__ , 'index.md' ) , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( 'The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') _lowercase = parser.parse_args() check_model_table(args.fix_and_overwrite)
22
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''PerceiverFeatureExtractor'''] _lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
22
1
"""simple docstring""" import math def _snake_case ( snake_case__ : int ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( snake_case__ : int = 1_0001 ): try: A = int(snake_case__ ) except (TypeError, ValueError): raise TypeError('Parameter nth must be int or castable to int.' ) from None if nth <= 0: raise ValueError('Parameter nth must be greater than or equal to one.' ) A = [] A = 2 while len(snake_case__ ) < nth: if is_prime(snake_case__ ): primes.append(snake_case__ ) num += 1 else: num += 1 return primes[len(snake_case__ ) - 1] if __name__ == "__main__": print(F"""{solution() = }""")
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _snake_case ( snake_case__ : int ): A = SwinvaConfig() A = swinva_name.split('_' ) A = name_split[1] if "to" in name_split[3]: A = int(name_split[3][-3:] ) else: A = int(name_split[3] ) if "to" in name_split[2]: A = int(name_split[2][-2:] ) else: A = int(name_split[2][6:] ) if model_size == "tiny": A = 96 A = (2, 2, 6, 2) A = (3, 6, 12, 24) elif model_size == "small": A = 96 A = (2, 2, 18, 2) A = (3, 6, 12, 24) elif model_size == "base": A = 128 A = (2, 2, 18, 2) A = (4, 8, 16, 32) else: A = 192 A = (2, 2, 18, 2) A = (6, 12, 24, 48) if "to" in swinva_name: A = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): A = 2_1841 A = 'huggingface/label-files' A = 'imagenet-22k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} else: A = 1000 A = 'huggingface/label-files' A = 'imagenet-1k-id2label.json' A = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) A = {int(snake_case__ ): v for k, v in idalabel.items()} A = idalabel A = {v: k for k, v in idalabel.items()} A = img_size A = num_classes A = embed_dim A = depths A = num_heads A = window_size return config def _snake_case ( snake_case__ : List[Any] ): if "patch_embed.proj" in name: A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: A = 'encoder.' + name if "attn.proj" in name: A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: A = name.replace('attn' , 'attention.self' ) if "norm1" in name: A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: A = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: A = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: A = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: A = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: A = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": A = 'layernorm.weight' if name == "norm.bias": A = 'layernorm.bias' if "head" in name: A = name.replace('head' , 'classifier' ) else: A = 'swinv2.' + name return name def _snake_case ( snake_case__ : List[Any] , snake_case__ : List[Any] ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "mask" in key: continue elif "qkv" in key: A = key.split('.' ) A = int(key_split[1] ) A = int(key_split[3] ) A = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = val return orig_state_dict def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Tuple ): A = timm.create_model(snake_case__ , pretrained=snake_case__ ) timm_model.eval() A = get_swinva_config(snake_case__ ) A = SwinvaForImageClassification(snake_case__ ) model.eval() A = convert_state_dict(timm_model.state_dict() , snake_case__ ) model.load_state_dict(snake_case__ ) A = 'http://images.cocodataset.org/val2017/000000039769.jpg' A = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) A = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) A = image_processor(images=snake_case__ , return_tensors='pt' ) A = timm_model(inputs['pixel_values'] ) A = model(**snake_case__ ).logits assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) model.push_to_hub( repo_path_or_name=Path(snake_case__ , snake_case__ ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
22
1
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''EleutherAI/gpt-j-6B''': '''https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json''', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: str = '''gptj''' _lowerCamelCase: Tuple = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : str ,A_ : Tuple=5_0400 ,A_ : Union[str, Any]=2048 ,A_ : Tuple=4096 ,A_ : Any=28 ,A_ : List[str]=16 ,A_ : Tuple=64 ,A_ : List[str]=None ,A_ : Optional[int]="gelu_new" ,A_ : Tuple=0.0 ,A_ : Union[str, Any]=0.0 ,A_ : Tuple=0.0 ,A_ : Optional[int]=1e-5 ,A_ : str=0.02 ,A_ : Optional[Any]=True ,A_ : Optional[Any]=5_0256 ,A_ : List[Any]=5_0256 ,A_ : Any=False ,**A_ : int ,) -> int: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = rotary_dim A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = use_cache A = bos_token_id A = eos_token_id super().__init__( bos_token_id=A_ ,eos_token_id=A_ ,tie_word_embeddings=A_ ,**A_ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,A_ : PretrainedConfig ,A_ : str = "default" ,A_ : List[PatchingSpec] = None ,A_ : bool = False ,) -> Union[str, Any]: super().__init__(A_ ,task=A_ ,patching_specs=A_ ,use_past=A_ ) if not getattr(self._config ,'pad_token_id' ,A_ ): # TODO: how to do that better? A = 0 @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: A = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(A_ ,direction='inputs' ) A = {0: 'batch', 1: 'past_sequence + sequence'} else: A = {0: 'batch', 1: 'sequence'} return common_inputs @property def _SCREAMING_SNAKE_CASE ( self : str ) -> int: return self._config.n_layer @property def _SCREAMING_SNAKE_CASE ( self : int ) -> int: return self._config.n_head def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : PreTrainedTokenizer ,A_ : int = -1 ,A_ : int = -1 ,A_ : bool = False ,A_ : Optional[TensorType] = None ,) -> Mapping[str, Any]: A = super(A_ ,self ).generate_dummy_inputs( A_ ,batch_size=A_ ,seq_length=A_ ,is_pair=A_ ,framework=A_ ) # We need to order the input in the way they appears in the forward() A = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch A , A = common_inputs['input_ids'].shape # Not using the same length for past_key_values A = seqlen + 2 A = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) A = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(self.num_layers ) ] A = common_inputs['attention_mask'] if self.use_past: A = ordered_inputs['attention_mask'].dtype A = torch.cat( [ordered_inputs['attention_mask'], torch.ones(A_ ,A_ ,dtype=A_ )] ,dim=1 ) return ordered_inputs @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: return 13
22
"""simple docstring""" from math import pi, sqrt def _snake_case ( snake_case__ : float ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(snake_case__ ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(snake_case__ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _snake_case ( ): assert gamma(0.5 ) == sqrt(snake_case__ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input('''Gamma of: ''')) print(F"""gamma({num}) = {gamma(num)}""") print('''\nEnter 0 to exit...''')
22
1