code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = MBartConfig _SCREAMING_SNAKE_CASE :str = {} _SCREAMING_SNAKE_CASE :List[Any] = """gelu""" def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : Any = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : str = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : Tuple = pad_token_id SCREAMING_SNAKE_CASE__ : List[str] = bos_token_id def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE__ : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_mbart_inputs_dict(_a , _a , _a ) return config, inputs_dict def _a ( self , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFMBartModel(config=_a ).get_decoder() SCREAMING_SNAKE_CASE__ : Dict = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : int = inputs_dict["""attention_mask"""][:1, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict["""head_mask"""] SCREAMING_SNAKE_CASE__ : Any = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , head_mask=_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.to_tuple() SCREAMING_SNAKE_CASE__ : str = past_key_values[1] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , ) -> int: if attention_mask is None: SCREAMING_SNAKE_CASE__ : str = tf.cast(tf.math.not_equal(__lowerCAmelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () _SCREAMING_SNAKE_CASE :str = (TFMBartForConditionalGeneration,) if is_tf_available() else () _SCREAMING_SNAKE_CASE :Tuple = ( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Dict = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self , _a , _a , _a , _a , _a ) -> Dict: """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFMBartModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=_a ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) @require_sentencepiece @require_tokenizers @require_tf class __a (unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = [ """ UN Chief Says There Is No Military Solution in Syria""", ] _SCREAMING_SNAKE_CASE :Any = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] _SCREAMING_SNAKE_CASE :Dict = """facebook/mbart-large-en-ro""" @cached_property def _a ( self ) -> List[str]: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.translate_src_text(**_a ) self.assertListEqual(self.expected_text , _a ) def _a ( self , **_a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer(self.src_text , **_a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer.batch_decode(_a , skip_special_tokens=_a ) return generated_words @slow def _a ( self ) -> List[Any]: """simple docstring""" self._assert_generated_batch_equal_expected()
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=2 , _a=32 , _a=16 , _a=3 , _a=True , _a=True , _a=32 , _a=4 , _a=[0, 1, 2, 3] , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=0.02 , _a=3 , _a=[1, 384, 24, 24] , _a=True , _a=None , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Dict = use_labels SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = backbone_out_indices SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE__ : str = backbone_featmap_shape SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : Union[str, Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Any = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Optional[int] = num_patches + 1 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any = self.get_config() return config, pixel_values, labels def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [96, 192, 384, 768], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=_a , backbone_featmap_shape=self.backbone_featmap_shape , ) def _a ( self , _a , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = DPTModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Dict = DPTForDepthEstimation(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def _a ( self , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.num_labels SCREAMING_SNAKE_CASE__ : List[str] = DPTForSemanticSegmentation(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () _SCREAMING_SNAKE_CASE :Union[str, Any] = ( { """depth-estimation""": DPTForDepthEstimation, """feature-extraction""": DPTModel, """image-segmentation""": DPTForSemanticSegmentation, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Any = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = DPTModelTester(self ) SCREAMING_SNAKE_CASE__ : Dict = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _a ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" pass def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*_a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = True if model_class in get_values(_a ): continue SCREAMING_SNAKE_CASE__ : Optional[Any] = model_class(_a ) model.to(_a ) model.train() SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(_a , _a , return_labels=_a ) SCREAMING_SNAKE_CASE__ : Any = model(**_a ).loss loss.backward() def _a ( self ) -> List[Any]: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = False SCREAMING_SNAKE_CASE__ : Tuple = True if model_class in get_values(_a ) or not model_class.supports_gradient_checkpointing: continue SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(_a ) model.to(_a ) model.gradient_checkpointing_enable() model.train() SCREAMING_SNAKE_CASE__ : Tuple = self._prepare_for_class(_a , _a , return_labels=_a ) SCREAMING_SNAKE_CASE__ : str = model(**_a ).loss loss.backward() def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = _config_zero_init(_a ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Any = model_class(config=_a ) # Skip the check for the backbone SCREAMING_SNAKE_CASE__ : List[str] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": SCREAMING_SNAKE_CASE__ : Tuple = [f'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _a ( self ) -> str: """simple docstring""" pass @slow def _a ( self ) -> List[Any]: """simple docstring""" for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: SCREAMING_SNAKE_CASE__ : int = DPTModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = """add""" with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : str = DPTForDepthEstimation(_a ) def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) SCREAMING_SNAKE_CASE__ : int = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**_a ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.predicted_depth # verify the predicted depth SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , _a ) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]] ).to(_a ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , _a , atol=1E-4 ) )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) a :List[str] = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"], "processing_speech_to_text": ["Speech2TextProcessor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = ["Speech2TextTokenizer"] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = ["Speech2TextFeatureExtractor"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Any = [ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = [ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" from __future__ import annotations import pandas as pd def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: SCREAMING_SNAKE_CASE__ : int = [0] * no_of_processes SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = burst_time[i] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Tuple = 9_9999_9999 SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Any = False # Process until all processes are completed while complete != no_of_processes: for j in range(__lowerCAmelCase ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: SCREAMING_SNAKE_CASE__ : Union[str, Any] = remaining_time[j] SCREAMING_SNAKE_CASE__ : Optional[Any] = j SCREAMING_SNAKE_CASE__ : Any = True if not check: increment_time += 1 continue remaining_time[short] -= 1 SCREAMING_SNAKE_CASE__ : Any = remaining_time[short] if minm == 0: SCREAMING_SNAKE_CASE__ : int = 9_9999_9999 if remaining_time[short] == 0: complete += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = False # Find finish time of current process SCREAMING_SNAKE_CASE__ : int = increment_time + 1 # Calculate waiting time SCREAMING_SNAKE_CASE__ : List[Any] = finish_time - arrival_time[short] SCREAMING_SNAKE_CASE__ : Dict = finar - burst_time[short] if waiting_time[short] < 0: SCREAMING_SNAKE_CASE__ : Tuple = 0 # Increment time increment_time += 1 return waiting_time def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: SCREAMING_SNAKE_CASE__ : str = [0] * no_of_processes for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = burst_time[i] + waiting_time[i] return turn_around_time def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : str = 0 for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = total_waiting_time + waiting_time[i] SCREAMING_SNAKE_CASE__ : Union[str, Any] = total_turn_around_time + turn_around_time[i] print(F'''Average waiting time = {total_waiting_time / no_of_processes:.5f}''' ) print("""Average turn around time =""" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print("Enter how many process you want to analyze") a :List[str] = int(input()) a :List[str] = [0] * no_of_processes a :Optional[Any] = [0] * no_of_processes a :str = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) a ,a :Tuple = map(int, input().split()) a :Tuple = calculate_waitingtime(arrival_time, burst_time, no_of_processes) a :Tuple = burst_time a :Optional[Any] = no_of_processes a :Union[str, Any] = waiting_time a :List[Any] = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) a :Optional[Any] = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : int = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = emb.weight.shape SCREAMING_SNAKE_CASE__ : Any = nn.Linear(__lowerCAmelCase , __lowerCAmelCase , bias=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = emb.weight.data return lin_layer def _lowercase ( __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : str = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] SCREAMING_SNAKE_CASE__ : Dict = mam_aaa["""model"""] remove_ignore_keys_(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict["""encoder.embed_tokens.weight"""].shape[0] SCREAMING_SNAKE_CASE__ : Dict = MaMaaaConfig( vocab_size=__lowerCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict["""decoder.embed_tokens.weight"""] SCREAMING_SNAKE_CASE__ : int = MaMaaaForConditionalGeneration(__lowerCAmelCase ) model.model.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a :str = argparse.ArgumentParser() # Required parameters parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") a :Union[str, Any] = parser.parse_args() a :Optional[Any] = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :UNetaDModel _SCREAMING_SNAKE_CASE :KarrasVeScheduler def __init__( self , _a , _a ) -> List[Any]: """simple docstring""" super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = 1 , _a = 50 , _a = None , _a = "pil" , _a = True , **_a , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.unet.config.sample_size SCREAMING_SNAKE_CASE__ : Optional[int] = (batch_size, 3, img_size, img_size) SCREAMING_SNAKE_CASE__ : Any = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) SCREAMING_SNAKE_CASE__ : List[Any] = randn_tensor(_a , generator=_a , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler.schedule[t] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler.add_noise_to_input(_a , _a , generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. SCREAMING_SNAKE_CASE__ : str = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler.step(_a , _a , _a , _a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. SCREAMING_SNAKE_CASE__ : str = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample SCREAMING_SNAKE_CASE__ : int = self.scheduler.step_correct( _a , _a , _a , _a , step_output.prev_sample , step_output["""derivative"""] , ) SCREAMING_SNAKE_CASE__ : str = step_output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = (sample / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : str = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : Optional[Any] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> list: SCREAMING_SNAKE_CASE__ : List[str] = int(__lowerCAmelCase ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError("""a should be a positive number""" ) raise my_error SCREAMING_SNAKE_CASE__ : int = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = (0, 0, 0) SCREAMING_SNAKE_CASE__ : List[str] = 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__": a :List[str] = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") a :str = hamming(int(n)) print("-----------------------------------------------------") print(f'The list with nth numbers is: {hamming_numbers}') print("-----------------------------------------------------")
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = KandinskyVaaPipeline _SCREAMING_SNAKE_CASE :List[Any] = [ """image_embeds""", """negative_image_embeds""", ] _SCREAMING_SNAKE_CASE :Any = ["""image_embeds""", """negative_image_embeds"""] _SCREAMING_SNAKE_CASE :List[Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _SCREAMING_SNAKE_CASE :List[Any] = False @property def _a ( self ) -> Optional[Any]: """simple docstring""" return 32 @property def _a ( self ) -> int: """simple docstring""" return 32 @property def _a ( self ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim @property def _a ( self ) -> Optional[int]: """simple docstring""" return self.time_input_dim * 4 @property def _a ( self ) -> List[str]: """simple docstring""" return 100 @property def _a ( self ) -> Any: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } SCREAMING_SNAKE_CASE__ : List[str] = UNetaDConditionModel(**_a ) return model @property def _a ( self ) -> List[str]: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _a ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = VQModel(**self.dummy_movq_kwargs ) return model def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_movq SCREAMING_SNAKE_CASE__ : str = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=_a , set_alpha_to_one=_a , steps_offset=1 , prediction_type="""epsilon""" , thresholding=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _a ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """cpu""" SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = self.pipeline_class(**_a ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : str = pipe(**self.get_dummy_inputs(_a ) ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Dict = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : int = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = KandinskyVaaPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Tuple = """red cat, 4k photo""" SCREAMING_SNAKE_CASE__ : str = torch.Generator(device="""cuda""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device="""cuda""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipeline( image_embeds=_a , negative_image_embeds=_a , generator=_a , num_inference_steps=100 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_a , _a )
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 0 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(_a , _a ) def _a ( self ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Dict = Path(_a ) / """preprocessor_config.json""" SCREAMING_SNAKE_CASE__ : Optional[Any] = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _a ( self ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path(_a ) / """preprocessor_config.json""" SCREAMING_SNAKE_CASE__ : Optional[Any] = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _a ( self ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : str = CLIPConfig() # Create a dummy config file with image_proceesor_type SCREAMING_SNAKE_CASE__ : Dict = Path(_a ) / """preprocessor_config.json""" SCREAMING_SNAKE_CASE__ : int = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally SCREAMING_SNAKE_CASE__ : str = AutoImageProcessor.from_pretrained(_a ).to_dict() config_dict.pop("""image_processor_type""" ) SCREAMING_SNAKE_CASE__ : Any = CLIPImageProcessor(**_a ) # save in new folder model_config.save_pretrained(_a ) config.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Dict = AutoImageProcessor.from_pretrained(_a ) # make sure private variable is not incorrectly saved SCREAMING_SNAKE_CASE__ : Tuple = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_a , _a ) def _a ( self ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Tuple = Path(_a ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) SCREAMING_SNAKE_CASE__ : List[str] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" with self.assertRaisesRegex( _a , """clip-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE__ : List[str] = AutoImageProcessor.from_pretrained("""clip-base""" ) def _a ( self ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex( _a , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE__ : List[Any] = AutoImageProcessor.from_pretrained(_a , revision="""aaaaaa""" ) def _a ( self ) -> Optional[Any]: """simple docstring""" with self.assertRaisesRegex( _a , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): SCREAMING_SNAKE_CASE__ : int = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def _a ( self ) -> Tuple: """simple docstring""" with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Dict = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) SCREAMING_SNAKE_CASE__ : Any = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Tuple = AutoImageProcessor.from_pretrained(_a , trust_remote_code=_a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def _a ( self ) -> int: """simple docstring""" try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoImageProcessor.register(_a , _a ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Optional[int] = Path(_a ) / """preprocessor_config.json""" SCREAMING_SNAKE_CASE__ : List[str] = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = CustomImageProcessor.from_pretrained(_a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _a ( self ) -> Any: """simple docstring""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = True try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE__ : List[Any] = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE__ : str = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE__ : Optional[int] = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(_a , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
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 a :str = logging.get_logger(__name__) if is_vision_available(): import PIL class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""pixel_values"""] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BICUBIC , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , _a = True , **_a , ) -> None: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = size if size is not None else {"""shortest_edge""": 224} SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(_a , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : int = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} SCREAMING_SNAKE_CASE__ : int = get_size_dict(_a , default_to_square=_a , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE__ : List[Any] = do_resize SCREAMING_SNAKE_CASE__ : str = size SCREAMING_SNAKE_CASE__ : Optional[int] = resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_center_crop SCREAMING_SNAKE_CASE__ : str = crop_size SCREAMING_SNAKE_CASE__ : Optional[int] = do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : List[str] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN SCREAMING_SNAKE_CASE__ : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD SCREAMING_SNAKE_CASE__ : Any = do_convert_rgb def _a ( self , _a , _a , _a = PILImageResampling.BICUBIC , _a = None , **_a , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(_a , default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 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 _a ( self , _a , _a , _a = None , **_a , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 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 _a ( self , _a , _a , _a = None , **_a , ) -> List[Any]: """simple docstring""" return rescale(_a , scale=_a , data_format=_a , **_a ) def _a ( self , _a , _a , _a , _a = None , **_a , ) -> np.ndarray: """simple docstring""" return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def _a ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Any = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Optional[Any] = get_size_dict(_a , param_name="""size""" , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : Tuple = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : List[Any] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Optional[Any] = get_size_dict(_a , param_name="""crop_size""" , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : List[str] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : int = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE__ : List[Any] = 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: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Optional[int] = [to_numpy_array(_a ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : int = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE__ : List[Any] = [self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : int = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Dict = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[int] = [to_channel_dimension_format(_a , _a ) for image in images] SCREAMING_SNAKE_CASE__ : Any = {"""pixel_values""": images} return BatchFeature(data=_a , tensor_type=_a )
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Union[str, Any] = sorted(numsa + numsa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = divmod(len(__lowerCAmelCase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() a :Any = [float(x) for x in input("Enter the elements of first array: ").split()] a :Tuple = [float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a :List[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """convbert""" def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-1_2 , _a=1 , _a=0 , _a=2 , _a=768 , _a=2 , _a=9 , _a=1 , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple = type_vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = embedding_size SCREAMING_SNAKE_CASE__ : Tuple = head_ratio SCREAMING_SNAKE_CASE__ : List[str] = conv_kernel_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_groups SCREAMING_SNAKE_CASE__ : Optional[Any] = classifier_dropout class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> list[int]: if num <= 0: raise ValueError("""Input must be a positive integer""" ) SCREAMING_SNAKE_CASE__ : Any = [True] * (num + 1) SCREAMING_SNAKE_CASE__ : str = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() a :Dict = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint 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." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput a :List[Any] = 8 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=BITS ) -> int: SCREAMING_SNAKE_CASE__ : Any = x.device SCREAMING_SNAKE_CASE__ : Optional[int] = (x * 255).int().clamp(0 , 255 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = rearrange(__lowerCAmelCase , """d -> d 1 1""" ) SCREAMING_SNAKE_CASE__ : Dict = rearrange(__lowerCAmelCase , """b c h w -> b c 1 h w""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ((x & mask) != 0).float() SCREAMING_SNAKE_CASE__ : List[Any] = rearrange(__lowerCAmelCase , """b c d h w -> b (c d) h w""" ) SCREAMING_SNAKE_CASE__ : List[str] = bits * 2 - 1 return bits def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=BITS ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[int] = x.device SCREAMING_SNAKE_CASE__ : Optional[Any] = (x > 0).int() SCREAMING_SNAKE_CASE__ : int = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__lowerCAmelCase , dtype=torch.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = rearrange(__lowerCAmelCase , """d -> d 1 1""" ) SCREAMING_SNAKE_CASE__ : int = rearrange(__lowerCAmelCase , """b (c d) h w -> b c d h w""" , d=8 ) SCREAMING_SNAKE_CASE__ : Optional[int] = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 255).clamp(0.0 , 1.0 ) def _lowercase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 0.0 , __lowerCAmelCase = True , __lowerCAmelCase=None , __lowerCAmelCase = True , ) -> Union[DDIMSchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) SCREAMING_SNAKE_CASE__ : List[str] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas SCREAMING_SNAKE_CASE__ : Tuple = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod SCREAMING_SNAKE_CASE__ : List[Any] = 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 SCREAMING_SNAKE_CASE__ : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" SCREAMING_SNAKE_CASE__ : str = self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Dict = torch.clamp(__lowerCAmelCase , -scale , __lowerCAmelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) SCREAMING_SNAKE_CASE__ : Dict = self._get_variance(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide SCREAMING_SNAKE_CASE__ : List[Any] = (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 SCREAMING_SNAKE_CASE__ : Optional[int] = (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 SCREAMING_SNAKE_CASE__ : Any = 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 SCREAMING_SNAKE_CASE__ : Tuple = model_output.device if torch.is_tensor(__lowerCAmelCase ) else """cpu""" SCREAMING_SNAKE_CASE__ : Optional[int] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__lowerCAmelCase ).to(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = self._get_variance(__lowerCAmelCase , __lowerCAmelCase ) ** 0.5 * eta * noise SCREAMING_SNAKE_CASE__ : Union[str, Any] = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__lowerCAmelCase , pred_original_sample=__lowerCAmelCase ) def _lowercase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase="epsilon" , __lowerCAmelCase=None , __lowerCAmelCase = True , ) -> Union[DDPMSchedulerOutput, Tuple]: SCREAMING_SNAKE_CASE__ : List[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = torch.split(__lowerCAmelCase , sample.shape[1] , dim=1 ) else: SCREAMING_SNAKE_CASE__ : Any = None # 1. compute alphas, betas SCREAMING_SNAKE_CASE__ : List[Any] = self.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.alphas_cumprod[t - 1] if t > 0 else self.one SCREAMING_SNAKE_CASE__ : List[str] = 1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : Optional[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Tuple = model_output else: raise ValueError(F'''Unsupported prediction_type {prediction_type}.''' ) # 3. Clip "predicted x_0" SCREAMING_SNAKE_CASE__ : List[str] = self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.clamp(__lowerCAmelCase , -scale , __lowerCAmelCase ) # 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 SCREAMING_SNAKE_CASE__ : Optional[Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t SCREAMING_SNAKE_CASE__ : Dict = 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 SCREAMING_SNAKE_CASE__ : Union[str, Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 if t > 0: SCREAMING_SNAKE_CASE__ : int = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__lowerCAmelCase ).to(model_output.device ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = (self._get_variance(__lowerCAmelCase , predicted_variance=__lowerCAmelCase ) ** 0.5) * noise SCREAMING_SNAKE_CASE__ : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__lowerCAmelCase , pred_original_sample=__lowerCAmelCase ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a , _a = 1.0 , ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Any = bit_scale SCREAMING_SNAKE_CASE__ : int = ( 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 , _a = 256 , _a = 256 , _a = 50 , _a = None , _a = 1 , _a = "pil" , _a = True , **_a , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=_a , ) SCREAMING_SNAKE_CASE__ : Tuple = decimal_to_bits(_a ) * self.bit_scale SCREAMING_SNAKE_CASE__ : List[str] = latents.to(self.device ) self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual SCREAMING_SNAKE_CASE__ : Dict = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler.step(_a , _a , _a ).prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = bits_to_decimal(_a ) if output_type == "pil": SCREAMING_SNAKE_CASE__ : Optional[int] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _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 , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor a :Dict = logging.get_logger(__name__) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , *_a , **_a ) -> None: """simple docstring""" warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" , _a , ) super().__init__(*_a , **_a )
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 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 if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" from random import shuffle import tensorflow as tf from numpy import array def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = int(__lowerCAmelCase ) assert noofclusters < len(__lowerCAmelCase ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : Optional[int] = len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : Optional[Any] = list(range(len(__lowerCAmelCase ) ) ) shuffle(__lowerCAmelCase ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : int = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : Tuple = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : List[str] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(__lowerCAmelCase ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("""float64""" , [dim] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for centroid in centroids: cent_assigns.append(tf.assign(__lowerCAmelCase , __lowerCAmelCase ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : Dict = [tf.Variable(0 ) for i in range(len(__lowerCAmelCase ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : int = tf.placeholder("""int32""" ) SCREAMING_SNAKE_CASE__ : Any = [] for assignment in assignments: cluster_assigns.append(tf.assign(__lowerCAmelCase , __lowerCAmelCase ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : str = tf.placeholder("""float""" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : str = tf.reduce_mean(__lowerCAmelCase , 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.placeholder("""float""" , [dim] ) SCREAMING_SNAKE_CASE__ : Dict = tf.placeholder("""float""" , [dim] ) SCREAMING_SNAKE_CASE__ : List[str] = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(__lowerCAmelCase , __lowerCAmelCase ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.placeholder("""float""" , [noofclusters] ) SCREAMING_SNAKE_CASE__ : Any = tf.argmin(__lowerCAmelCase , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.initialize_all_variables() # Initialize all variables sess.run(__lowerCAmelCase ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Tuple = 100 for _ in range(__lowerCAmelCase ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : List[str] = [ sess.run(__lowerCAmelCase , feed_dict={va: vect, va: sess.run(__lowerCAmelCase )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : List[str] = sess.run( __lowerCAmelCase , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(__lowerCAmelCase ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : Dict = [ vectors[i] for i in range(len(__lowerCAmelCase ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : List[str] = sess.run( __lowerCAmelCase , feed_dict={mean_input: array(__lowerCAmelCase )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : Dict = sess.run(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sess.run(__lowerCAmelCase ) return centroids, assignments
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel a :str = logging.getLogger(__name__) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: # save results if os.path.exists(__lowerCAmelCase ): if os.path.exists(os.path.join(__lowerCAmelCase , """config.json""" ) ) and os.path.isfile( os.path.join(__lowerCAmelCase , """config.json""" ) ): os.remove(os.path.join(__lowerCAmelCase , """config.json""" ) ) if os.path.exists(os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) ) and os.path.isfile( os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) ): os.remove(os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) ) else: os.makedirs(__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=False ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = 2 if unlogit: SCREAMING_SNAKE_CASE__ : List[Any] = torch.pow(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = p * torch.log(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = 0 return -plogp.sum(dim=-1 ) def _lowercase ( __lowerCAmelCase ) -> List[Any]: logger.info("""lv, h >\t""" + """\t""".join(F'''{x + 1}''' for x in range(len(__lowerCAmelCase ) ) ) ) for row in range(len(__lowerCAmelCase ) ): if tensor.dtype != torch.long: logger.info(F'''layer {row + 1}:\t''' + """\t""".join(F'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(F'''layer {row + 1}:\t''' + """\t""".join(F'''{x:d}''' for x in tensor[row].cpu().data ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=None , __lowerCAmelCase=False ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.config.num_hidden_layers, model.config.num_attention_heads SCREAMING_SNAKE_CASE__ : str = torch.zeros(__lowerCAmelCase , __lowerCAmelCase ).to(args.device ) SCREAMING_SNAKE_CASE__ : int = torch.zeros(__lowerCAmelCase , __lowerCAmelCase ).to(args.device ) if head_mask is None: SCREAMING_SNAKE_CASE__ : int = torch.ones(__lowerCAmelCase , __lowerCAmelCase ).to(args.device ) head_mask.requires_grad_(requires_grad=__lowerCAmelCase ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.0 SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0 for step, inputs in enumerate(tqdm(__lowerCAmelCase , desc="""Iteration""" , disable=args.local_rank not in [-1, 0] ) ): SCREAMING_SNAKE_CASE__ : Optional[int] = tuple(t.to(args.device ) for t in inputs ) ((SCREAMING_SNAKE_CASE__) , ) : Optional[int] = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) SCREAMING_SNAKE_CASE__ : Optional[int] = model(__lowerCAmelCase , labels=__lowerCAmelCase , head_mask=__lowerCAmelCase ) # (loss), lm_logits, presents, (all hidden_states), (attentions) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = entropy(attn.detach() , __lowerCAmelCase ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(__lowerCAmelCase ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: SCREAMING_SNAKE_CASE__ : Dict = 2 SCREAMING_SNAKE_CASE__ : Any = torch.pow(torch.pow(__lowerCAmelCase , __lowerCAmelCase ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info("""Attention entropies""" ) print_ad_tensor(__lowerCAmelCase ) if compute_importance: logger.info("""Head importance scores""" ) print_ad_tensor(__lowerCAmelCase ) logger.info("""Head ranked by importance scores""" ) SCREAMING_SNAKE_CASE__ : Any = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) SCREAMING_SNAKE_CASE__ : Tuple = torch.arange( head_importance.numel() , device=args.device ) SCREAMING_SNAKE_CASE__ : int = head_ranks.view_as(__lowerCAmelCase ) print_ad_tensor(__lowerCAmelCase ) return attn_entropy, head_importance, total_loss def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = compute_heads_importance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , compute_entropy=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = 1 / loss # instead of downsteam score use the LM loss logger.info("""Pruning: original score: %f, threshold: %f""" , __lowerCAmelCase , original_score * args.masking_threshold ) SCREAMING_SNAKE_CASE__ : int = torch.ones_like(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) SCREAMING_SNAKE_CASE__ : Dict = original_score while current_score >= original_score * args.masking_threshold: SCREAMING_SNAKE_CASE__ : List[Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads SCREAMING_SNAKE_CASE__ : Tuple = float("""Inf""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = head_importance.view(-1 ).sort()[1] if len(__lowerCAmelCase ) <= num_to_mask: print("""BREAK BY num_to_mask""" ) break # mask heads SCREAMING_SNAKE_CASE__ : List[Any] = current_heads_to_mask[:num_to_mask] logger.info("""Heads to mask: %s""" , str(current_heads_to_mask.tolist() ) ) SCREAMING_SNAKE_CASE__ : str = new_head_mask.view(-1 ) SCREAMING_SNAKE_CASE__ : List[str] = 0.0 SCREAMING_SNAKE_CASE__ : List[str] = new_head_mask.view_as(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = new_head_mask.clone().detach() print_ad_tensor(__lowerCAmelCase ) # Compute metric and head importance again SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = compute_heads_importance( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , compute_entropy=__lowerCAmelCase , head_mask=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 1 / loss logger.info( """Masking: current score: %f, remaining heads %d (%.1f percents)""" , __lowerCAmelCase , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info("""Final head mask""" ) print_ad_tensor(__lowerCAmelCase ) np.save(os.path.join(args.output_dir , """head_mask.npy""" ) , head_mask.detach().cpu().numpy() ) return head_mask def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = datetime.now() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_heads_importance( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , compute_entropy=__lowerCAmelCase , compute_importance=__lowerCAmelCase , head_mask=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = 1 / loss SCREAMING_SNAKE_CASE__ : Dict = datetime.now() - before_time SCREAMING_SNAKE_CASE__ : int = sum(p.numel() for p in model.parameters() ) SCREAMING_SNAKE_CASE__ : Optional[int] = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__lowerCAmelCase ) ) } for k, v in heads_to_prune.items(): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [ v, ] assert sum(len(__lowerCAmelCase ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sum(p.numel() for p in model.parameters() ) SCREAMING_SNAKE_CASE__ : Optional[int] = datetime.now() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_heads_importance( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , compute_entropy=__lowerCAmelCase , compute_importance=__lowerCAmelCase , head_mask=__lowerCAmelCase , actually_pruned=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : str = 1 / loss SCREAMING_SNAKE_CASE__ : Union[str, Any] = datetime.now() - before_time logger.info( """Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)""" , __lowerCAmelCase , __lowerCAmelCase , pruned_num_params / original_num_params * 100 , ) logger.info("""Pruning: score with masking: %f score with pruning: %f""" , __lowerCAmelCase , __lowerCAmelCase ) logger.info("""Pruning: speed ratio (original timing / new timing): %f percents""" , original_time / new_time * 100 ) save_model(__lowerCAmelCase , args.output_dir ) def _lowercase ( ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--data_dir""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""The input data dir. Should contain the .tsv files (or other data files) for the task.""" , ) parser.add_argument( """--model_name_or_path""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--output_dir""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""The output directory where the model predictions and checkpoints will be written.""" , ) # Other parameters parser.add_argument( """--config_name""" , default="""""" , type=__lowerCAmelCase , help="""Pretrained config name or path if not the same as model_name_or_path""" , ) parser.add_argument( """--tokenizer_name""" , default="""""" , type=__lowerCAmelCase , help="""Pretrained tokenizer name or path if not the same as model_name_or_path""" , ) parser.add_argument( """--cache_dir""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""Where do you want to store the pre-trained models downloaded from s3""" , ) parser.add_argument( """--data_subset""" , type=__lowerCAmelCase , default=-1 , help="""If > 0: limit the data to a subset of data_subset instances.""" ) parser.add_argument( """--overwrite_output_dir""" , action="""store_true""" , help="""Whether to overwrite data in output directory""" ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) parser.add_argument( """--dont_normalize_importance_by_layer""" , action="""store_true""" , help="""Don't normalize importance score by layers""" ) parser.add_argument( """--dont_normalize_global_importance""" , action="""store_true""" , help="""Don't normalize all importance scores between 0 and 1""" , ) parser.add_argument( """--try_masking""" , action="""store_true""" , help="""Whether to try to mask head until a threshold of accuracy.""" ) parser.add_argument( """--masking_threshold""" , default=0.9 , type=__lowerCAmelCase , help="""masking threshold in term of metrics (stop masking when metric < threshold * original metric value).""" , ) parser.add_argument( """--masking_amount""" , default=0.1 , type=__lowerCAmelCase , help="""Amount to heads to masking at each masking step.""" ) parser.add_argument("""--metric_name""" , default="""acc""" , type=__lowerCAmelCase , help="""Metric to use for head masking.""" ) parser.add_argument( """--max_seq_length""" , default=128 , type=__lowerCAmelCase , help=( """The maximum total input sequence length after WordPiece tokenization. \n""" """Sequences longer than this will be truncated, sequences shorter padded.""" ) , ) parser.add_argument("""--batch_size""" , default=1 , type=__lowerCAmelCase , help="""Batch size.""" ) parser.add_argument("""--seed""" , type=__lowerCAmelCase , default=42 ) parser.add_argument("""--local_rank""" , type=__lowerCAmelCase , default=-1 , help="""local_rank for distributed training on gpus""" ) parser.add_argument("""--no_cuda""" , action="""store_true""" , help="""Whether not to use CUDA when available""" ) parser.add_argument("""--server_ip""" , type=__lowerCAmelCase , default="""""" , help="""Can be used for distant debugging.""" ) parser.add_argument("""--server_port""" , type=__lowerCAmelCase , default="""""" , help="""Can be used for distant debugging.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("""Waiting for debugger attach""" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__lowerCAmelCase ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu""" ) SCREAMING_SNAKE_CASE__ : Any = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.device("""cuda""" , args.local_rank ) SCREAMING_SNAKE_CASE__ : Any = 1 torch.distributed.init_process_group(backend="""nccl""" ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info("""device: {} n_gpu: {}, distributed: {}""".format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) SCREAMING_SNAKE_CASE__ : Dict = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.parallel.DistributedDataParallel( __lowerCAmelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=__lowerCAmelCase ) elif args.n_gpu > 1: SCREAMING_SNAKE_CASE__ : str = nn.DataParallel(__lowerCAmelCase ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=__lowerCAmelCase ) torch.save(__lowerCAmelCase , os.path.join(args.output_dir , """run_args.bin""" ) ) logger.info("""Training/evaluation parameters %s""" , __lowerCAmelCase ) # Prepare dataset SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) SCREAMING_SNAKE_CASE__ : Optional[int] = (torch.from_numpy(__lowerCAmelCase ),) SCREAMING_SNAKE_CASE__ : Any = TensorDataset(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = RandomSampler(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = DataLoader(__lowerCAmelCase , sampler=__lowerCAmelCase , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: SCREAMING_SNAKE_CASE__ : int = mask_heads(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) prune_heads(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=1024 ) -> Tuple: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = [], [] SCREAMING_SNAKE_CASE__ : List[Any] = list(zip(__lowerCAmelCase , __lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = sorted_examples[0] def is_too_big(__lowerCAmelCase ): return tok(__lowerCAmelCase , return_tensors="""pt""" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): SCREAMING_SNAKE_CASE__ : Dict = new_src + """ """ + src SCREAMING_SNAKE_CASE__ : Any = new_tgt + """ """ + tgt if is_too_big(__lowerCAmelCase ) or is_too_big(__lowerCAmelCase ): # cant fit, finalize example finished_src.append(__lowerCAmelCase ) finished_tgt.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = src, tgt else: # can fit, keep adding SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(__lowerCAmelCase ) finished_tgt.append(__lowerCAmelCase ) return finished_src, finished_tgt def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : int = Path(__lowerCAmelCase ) save_path.mkdir(exist_ok=__lowerCAmelCase ) for split in ["train"]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = data_dir / F'''{split}.source''', data_dir / F'''{split}.target''' SCREAMING_SNAKE_CASE__ : str = [x.rstrip() for x in Path(__lowerCAmelCase ).open().readlines()] SCREAMING_SNAKE_CASE__ : int = [x.rstrip() for x in Path(__lowerCAmelCase ).open().readlines()] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = pack_examples(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) print(F'''packed {split} split from {len(__lowerCAmelCase )} examples -> {len(__lowerCAmelCase )}.''' ) Path(save_path / F'''{split}.source''' ).open("""w""" ).write("""\n""".join(__lowerCAmelCase ) ) Path(save_path / F'''{split}.target''' ).open("""w""" ).write("""\n""".join(__lowerCAmelCase ) ) for split in ["val", "test"]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = data_dir / F'''{split}.source''', data_dir / F'''{split}.target''' shutil.copyfile(__lowerCAmelCase , save_path / F'''{split}.source''' ) shutil.copyfile(__lowerCAmelCase , save_path / F'''{split}.target''' ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument("""--tok_name""" , type=__lowerCAmelCase , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""--max_seq_len""" , type=__lowerCAmelCase , default=128 ) parser.add_argument("""--data_dir""" , type=__lowerCAmelCase ) parser.add_argument("""--save_path""" , type=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_args() SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(__lowerCAmelCase , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" import math def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 0 , __lowerCAmelCase = 0 ) -> list: SCREAMING_SNAKE_CASE__ : int = end or len(__lowerCAmelCase ) for i in range(__lowerCAmelCase , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = i SCREAMING_SNAKE_CASE__ : Optional[int] = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = array[temp_index - 1] temp_index -= 1 SCREAMING_SNAKE_CASE__ : Optional[int] = temp_index_value return array def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: # Max Heap SCREAMING_SNAKE_CASE__ : Any = index SCREAMING_SNAKE_CASE__ : str = 2 * index + 1 # Left Node SCREAMING_SNAKE_CASE__ : Optional[Any] = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: SCREAMING_SNAKE_CASE__ : List[str] = left_index if right_index < heap_size and array[largest] < array[right_index]: SCREAMING_SNAKE_CASE__ : Any = right_index if largest != index: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = array[largest], array[index] heapify(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase ) -> list: SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) for i in range(n // 2 , -1 , -1 ): heapify(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for i in range(n - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = array[0], array[i] heapify(__lowerCAmelCase , 0 , __lowerCAmelCase ) return array def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Union[str, Any] = low SCREAMING_SNAKE_CASE__ : Any = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = array[j], array[i] i += 1 def _lowercase ( __lowerCAmelCase ) -> list: if len(__lowerCAmelCase ) == 0: return array SCREAMING_SNAKE_CASE__ : str = 2 * math.ceil(math.loga(len(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = 16 return intro_sort(__lowerCAmelCase , 0 , len(__lowerCAmelCase ) , __lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> list: while end - start > size_threshold: if max_depth == 0: return heap_sort(__lowerCAmelCase ) max_depth -= 1 SCREAMING_SNAKE_CASE__ : Tuple = median_of_a(__lowerCAmelCase , __lowerCAmelCase , start + ((end - start) // 2) + 1 , end - 1 ) SCREAMING_SNAKE_CASE__ : Tuple = partition(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) intro_sort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = p return insertion_sort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() a :Tuple = input("Enter numbers separated by a comma : ").strip() a :Optional[int] = [float(item) for item in user_input.split(",")] print(sort(unsorted))
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 a :Tuple = sys.version_info >= (3, 10) def _lowercase ( __lowerCAmelCase=None , __lowerCAmelCase=None ) -> List[Any]: return field(default_factory=lambda: default , metadata=__lowerCAmelCase ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :int _SCREAMING_SNAKE_CASE :float _SCREAMING_SNAKE_CASE :str _SCREAMING_SNAKE_CASE :bool @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :int = 42 _SCREAMING_SNAKE_CASE :str = field(default="""toto""" , metadata={"""help""": """help message"""}) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[bool] = None class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """titi""" _SCREAMING_SNAKE_CASE :Union[str, Any] = """toto""" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = """titi""" _SCREAMING_SNAKE_CASE :Any = """toto""" _SCREAMING_SNAKE_CASE :List[str] = 42 @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :BasicEnum = "toto" def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BasicEnum(self.foo ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :MixedTypeEnum = "toto" def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = MixedTypeEnum(self.foo ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :Optional[float] = field(default=UpperCamelCase_ , metadata={"""help""": """help message"""}) _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :Optional[List[str]] = list_field(default=[]) _SCREAMING_SNAKE_CASE :Optional[List[int]] = list_field(default=[]) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :List[int] = list_field(default=[]) _SCREAMING_SNAKE_CASE :List[int] = list_field(default=[1, 2, 3]) _SCREAMING_SNAKE_CASE :List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) _SCREAMING_SNAKE_CASE :List[float] = list_field(default=[0.1, 0.2, 0.3]) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :List[int] = field() _SCREAMING_SNAKE_CASE :str = field() _SCREAMING_SNAKE_CASE :BasicEnum = field() def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BasicEnum(self.required_enum ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :int _SCREAMING_SNAKE_CASE :"BasicEnum" = field() _SCREAMING_SNAKE_CASE :"Optional[bool]" = None _SCREAMING_SNAKE_CASE :"str" = field(default="""toto""" , metadata={"""help""": """help message"""}) _SCREAMING_SNAKE_CASE :"List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""]) if is_python_no_less_than_3_10: @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :bool | None = None @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :int | None = None _SCREAMING_SNAKE_CASE :float | None = field(default=UpperCamelCase_ , metadata={"""help""": """help message"""}) _SCREAMING_SNAKE_CASE :str | None = None _SCREAMING_SNAKE_CASE :list[str] | None = list_field(default=[]) _SCREAMING_SNAKE_CASE :list[int] | None = list_field(default=[]) class __a (unittest.TestCase): '''simple docstring''' def _a ( self , _a , _a ) -> Dict: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): SCREAMING_SNAKE_CASE__ : Any = {k: v for k, v in vars(_a ).items() if k != """container"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = {k: v for k, v in vars(_a ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , _a ) and yy.get("""choices""" , _a ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](_a ) , yy["""type"""](_a ) ) del xx["type"], yy["type"] self.assertEqual(_a , _a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , required=_a ) expected.add_argument("""--bar""" , type=_a , required=_a ) expected.add_argument("""--baz""" , type=_a , required=_a ) expected.add_argument("""--flag""" , type=_a , default=_a , const=_a , nargs="""?""" ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((SCREAMING_SNAKE_CASE__) , ) : Optional[int] = parser.parse_args_into_dataclasses(_a , look_for_args_file=_a ) self.assertFalse(example.flag ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=_a ) expected.add_argument("""--baz""" , default="""toto""" , type=_a , help="""help message""" ) self.argparsersEqual(_a , _a ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , default=_a , const=_a , nargs="""?""" ) expected.add_argument("""--baz""" , type=_a , default=_a , const=_a , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=_a , dest="""baz""" ) expected.add_argument("""--opt""" , type=_a , default=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ : List[Any] = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) SCREAMING_SNAKE_CASE__ : int = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) SCREAMING_SNAKE_CASE__ : int = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def _a ( self ) -> Union[str, Any]: """simple docstring""" @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Literal["titi", "toto", 42] = "toto" SCREAMING_SNAKE_CASE__ : str = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Any = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=_a ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=_a ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=_a ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=_a ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args([] ) self.assertEqual( _a , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(_a , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=_a , type=_a ) expected.add_argument("""--bar""" , default=_a , type=_a , help="""help message""" ) expected.add_argument("""--baz""" , default=_a , type=_a ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=_a ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ : Dict = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , bar=_a , baz=_a , ces=[] , des=[] ) ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(_a , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=_a , required=_a ) expected.add_argument("""--required_str""" , type=_a , required=_a ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=_a , ) self.argparsersEqual(_a , _a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , required=_a ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=_a , ) expected.add_argument("""--opt""" , type=_a , default=_a ) expected.add_argument("""--baz""" , default="""toto""" , type=_a , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=_a ) self.argparsersEqual(_a , _a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_dict(_a )[0] SCREAMING_SNAKE_CASE__ : str = BasicExample(**_a ) self.assertEqual(_a , _a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : str = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(_a , parser.parse_dict , _a , allow_extra_keys=_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Any = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : str = os.path.join(_a , """temp_json""" ) os.mkdir(_a ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(_a , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = BasicExample(**_a ) self.assertEqual(_a , _a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = HfArgumentParser(_a ) SCREAMING_SNAKE_CASE__ : Any = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , """temp_yaml""" ) os.mkdir(_a ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(_a , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] SCREAMING_SNAKE_CASE__ : int = BasicExample(**_a ) self.assertEqual(_a , _a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = HfArgumentParser(_a ) self.assertIsNotNone(_a )
680
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 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": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
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 __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 1 SCREAMING_SNAKE_CASE__ : int = 3 SCREAMING_SNAKE_CASE__ : List[Any] = (32, 32) SCREAMING_SNAKE_CASE__ : str = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_a ) return image @property def _a ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = 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 _a ( self ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = 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 _a ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(_a ) @property def _a ( self ) -> Optional[Any]: """simple docstring""" def extract(*_a , **_a ): class __a : '''simple docstring''' def __init__( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = torch.ones([0] ) def _a ( self , _a ) -> List[Any]: """simple docstring""" self.pixel_values.to(_a ) return self return Out() return extract def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_a , set_alpha_to_one=_a , ) SCREAMING_SNAKE_CASE__ : Any = self.dummy_vae SCREAMING_SNAKE_CASE__ : int = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : Any = StableDiffusionPipeline( unet=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , safety_checker=_a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Any = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ : int = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = sd_pipe([prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.images SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe( [prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=_a , )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) 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 _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : Optional[int] = PNDMScheduler(skip_prk_steps=_a ) SCREAMING_SNAKE_CASE__ : Tuple = self.dummy_vae SCREAMING_SNAKE_CASE__ : Dict = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : str = StableDiffusionPipeline( unet=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , safety_checker=_a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe([prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe( [prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=_a , )[0] SCREAMING_SNAKE_CASE__ : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) 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 _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 ) SCREAMING_SNAKE_CASE__ : str = StableDiffusionPipeline.from_pretrained(_a ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ : str = 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 _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ : Any = PNDMScheduler(skip_prk_steps=_a ) SCREAMING_SNAKE_CASE__ : int = self.dummy_vae SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 SCREAMING_SNAKE_CASE__ : int = unet.half() SCREAMING_SNAKE_CASE__ : Optional[Any] = vae.half() SCREAMING_SNAKE_CASE__ : Optional[int] = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ : Dict = StableDiffusionPipeline( unet=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , safety_checker=_a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ : Any = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : str = ( """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 """ ) SCREAMING_SNAKE_CASE__ : int = 4_003_660_346 SCREAMING_SNAKE_CASE__ : int = 7 # without safety guidance (sld_guidance_scale = 0) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ : str = output.images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) SCREAMING_SNAKE_CASE__ : List[Any] = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : int = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ : str = output.images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=_a ) SCREAMING_SNAKE_CASE__ : Tuple = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Dict = """padme amidala taking a bath artwork, safe for work, no nudity""" SCREAMING_SNAKE_CASE__ : Any = 2_734_971_755 SCREAMING_SNAKE_CASE__ : Optional[Any] = 7 SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ : str = output.images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) SCREAMING_SNAKE_CASE__ : Dict = 1_044_355_234 SCREAMING_SNAKE_CASE__ : Optional[Any] = 12 SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ : List[str] = output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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 SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe( [prompt] , generator=_a , guidance_scale=_a , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = """philschmid/bart-large-cnn-samsum""" _SCREAMING_SNAKE_CASE :Union[str, Any] = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) _SCREAMING_SNAKE_CASE :List[Any] = """summarizer""" _SCREAMING_SNAKE_CASE :Optional[Any] = AutoTokenizer _SCREAMING_SNAKE_CASE :List[str] = AutoModelForSeqaSeqLM _SCREAMING_SNAKE_CASE :List[Any] = ["""text"""] _SCREAMING_SNAKE_CASE :str = ["""text"""] def _a ( self , _a ) -> Dict: """simple docstring""" return self.pre_processor(_a , return_tensors="""pt""" , truncation=_a ) def _a ( self , _a ) -> List[Any]: """simple docstring""" return self.model.generate(**_a )[0] def _a ( self , _a ) -> List[Any]: """simple docstring""" return self.pre_processor.decode(_a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[Any] = 5 # Realm tok SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """test""", """question""", """this""", """is""", """the""", """first""", """second""", """third""", """fourth""", """fifth""", """record""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , """realm_tokenizer""" ) os.makedirs(_a , exist_ok=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(_a , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(self.tmpdirname , """realm_block_records""" ) os.makedirs(_a , exist_ok=_a ) def _a ( self ) -> RealmTokenizer: """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , """realm_tokenizer""" ) ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = RealmConfig(num_block_records=self.num_block_records ) return config def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = Dataset.from_dict( { """id""": ["""0""", """1"""], """question""": ["""foo""", """bar"""], """answers""": [["""Foo""", """Bar"""], ["""Bar"""]], } ) return dataset def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = np.array( [ B"""This is the first record""", B"""This is the second record""", B"""This is the third record""", B"""This is the fourth record""", B"""This is the fifth record""", B"""This is a longer longer longer record""", ] , dtype=_a , ) return block_records def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_config() SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_retriever() SCREAMING_SNAKE_CASE__ : List[str] = retriever.tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([0, 3] , dtype="""long""" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(["""Test question"""] ).input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer( ["""the fourth"""] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = config.reader_seq_len SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors="""np""" ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """first""", """record""", """[SEP]"""] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """fourth""", """record""", """[SEP]"""] , ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_config() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_retriever() SCREAMING_SNAKE_CASE__ : str = retriever.tokenizer SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 3, 5] , dtype="""long""" ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(["""Test question"""] ).input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer( ["""the fourth""", """longer longer"""] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids SCREAMING_SNAKE_CASE__ : List[Any] = config.reader_seq_len SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors="""np""" ) self.assertEqual([False, True, True] , _a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , _a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , _a ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) # Test local path SCREAMING_SNAKE_CASE__ : Union[str, Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) self.assertEqual(retriever.block_records[0] , B"""This is the first record""" ) # Test mocked remote path with patch("""transformers.models.realm.retrieval_realm.hf_hub_download""" ) as mock_hf_hub_download: SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join( os.path.join(self.tmpdirname , """realm_block_records""" ) , _REALM_BLOCK_RECORDS_FILENAME ) SCREAMING_SNAKE_CASE__ : List[str] = RealmRetriever.from_pretrained("""google/realm-cc-news-pretrained-openqa""" ) self.assertEqual(retriever.block_records[0] , B"""This is the first record""" )
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a :Optional[Any] = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = [ "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST", "NezhaForNextSentencePrediction", "NezhaForMaskedLM", "NezhaForPreTraining", "NezhaForMultipleChoice", "NezhaForQuestionAnswering", "NezhaForSequenceClassification", "NezhaForTokenClassification", "NezhaModel", "NezhaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys a :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" import numpy as np def _lowercase ( __lowerCAmelCase ) -> np.ndarray: return 1 / (1 + np.exp(-vector )) def _lowercase ( __lowerCAmelCase ) -> np.ndarray: return vector * sigmoid(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ["""flax""", """transformers"""] def __init__( self , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Any: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Optional[Any]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""flax""", """transformers"""] def __init__( self , *_a , **_a ) -> Dict: """simple docstring""" requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ["""flax""", """transformers"""] def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Any: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) class __a (metaclass=UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ["""flax""", """transformers"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> List[str]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def _a ( cls , *_a , **_a ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["""flax""", """transformers"""] )
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a :Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = ["NllbTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = ["NllbTokenizerFast"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """Wav2Vec2FeatureExtractor""" _SCREAMING_SNAKE_CASE :Union[str, Any] = """AutoTokenizer""" def __init__( self , _a , _a ) -> Tuple: """simple docstring""" super().__init__(_a , _a ) SCREAMING_SNAKE_CASE__ : int = self.feature_extractor SCREAMING_SNAKE_CASE__ : Union[str, Any] = False @classmethod def _a ( cls , _a , **_a ) -> List[str]: """simple docstring""" try: return super().from_pretrained(_a , **_a ) except OSError: warnings.warn( f'''Loading a tokenizer inside {cls.__name__} from a config that does not''' """ include a `tokenizer_class` attribute is deprecated and will be """ """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`""" """ attribute to either your `config.json` or `tokenizer_config.json` """ """file to suppress this warning: """ , _a , ) SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaFeatureExtractor.from_pretrained(_a , **_a ) SCREAMING_SNAKE_CASE__ : Tuple = WavaVecaCTCTokenizer.from_pretrained(_a , **_a ) return cls(feature_extractor=_a , tokenizer=_a ) def __call__( self , *_a , **_a ) -> List[Any]: """simple docstring""" if self._in_target_context_manager: return self.current_processor(*_a , **_a ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop("""raw_speech""" ) else: SCREAMING_SNAKE_CASE__ : Any = kwargs.pop("""audio""" , _a ) SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop("""sampling_rate""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("""text""" , _a ) if len(_a ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extractor(_a , *_a , sampling_rate=_a , **_a ) if text is not None: SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer(_a , **_a ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : Optional[Any] = encodings["""input_ids"""] return inputs def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self._in_target_context_manager: return self.current_processor.pad(*_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop("""input_features""" , _a ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop("""labels""" , _a ) if len(_a ) > 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = args[0] SCREAMING_SNAKE_CASE__ : List[Any] = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor.pad(_a , *_a , **_a ) if labels is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.pad(_a , **_a ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE__ : int = labels["""input_ids"""] return input_features def _a ( self , *_a , **_a ) -> Tuple: """simple docstring""" return self.tokenizer.batch_decode(*_a , **_a ) def _a ( self , *_a , **_a ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*_a , **_a ) @contextmanager def _a ( self ) -> Union[str, Any]: """simple docstring""" warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : str = self.feature_extractor SCREAMING_SNAKE_CASE__ : Tuple = False
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
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 a :List[Any] = logging.get_logger(__name__) a :str = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = """mobilenet_v2""" def __init__( self , _a=3 , _a=224 , _a=1.0 , _a=8 , _a=8 , _a=6 , _a=32 , _a=True , _a=True , _a="relu6" , _a=True , _a=0.8 , _a=0.02 , _a=0.001 , _a=255 , **_a , ) -> int: """simple docstring""" super().__init__(**_a ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = depth_multiplier SCREAMING_SNAKE_CASE__ : Optional[int] = depth_divisible_by SCREAMING_SNAKE_CASE__ : int = min_depth SCREAMING_SNAKE_CASE__ : Optional[int] = expand_ratio SCREAMING_SNAKE_CASE__ : Dict = output_stride SCREAMING_SNAKE_CASE__ : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE__ : str = finegrained_output SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Any = tf_padding SCREAMING_SNAKE_CASE__ : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = semantic_loss_ignore_index class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = version.parse("""1.11""") @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def _a ( self ) -> float: """simple docstring""" return 1E-4
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" import unittest from transformers import AutoTokenizer, FalconConfig, 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 ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class __a : '''simple docstring''' def __init__( self , _a , _a=3 , _a=7 , _a=True , _a=True , _a=False , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Any = seq_length SCREAMING_SNAKE_CASE__ : Union[str, Any] = is_training SCREAMING_SNAKE_CASE__ : int = use_input_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : int = num_choices SCREAMING_SNAKE_CASE__ : Any = scope def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Dict = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> Optional[Any]: """simple docstring""" return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=_a , ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = FalconModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , attention_mask=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = FalconModel(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = model( _a , attention_mask=_a , encoder_hidden_states=_a , ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = FalconForCausalLM(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Tuple = FalconForCausalLM(config=_a ) model.to(_a ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ : Dict = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , use_cache=_a , ) SCREAMING_SNAKE_CASE__ : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model( _a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , output_hidden_states=_a , )["""hidden_states"""][0] SCREAMING_SNAKE_CASE__ : Optional[int] = 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 SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : int = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Any = config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Dict = (FalconForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :Dict = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Any = False _SCREAMING_SNAKE_CASE :Tuple = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = FalconModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: SCREAMING_SNAKE_CASE__ : Dict = alibi self.model_tester.create_and_check_model(_a , *_a ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : List[str] = """single_label_classification""" SCREAMING_SNAKE_CASE__ : int = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Tuple = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Any = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = FalconForCausalLM(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : Any = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Dict = model._convert_to_rw_cache(result.past_key_values ) SCREAMING_SNAKE_CASE__ : Tuple = model._convert_cache_to_standard_format(_a , _a ) for layer in range(len(_a ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : int = """multi_label_classification""" SCREAMING_SNAKE_CASE__ : str = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : List[Any] = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : int = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : List[Any] = FalconForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> str: """simple docstring""" for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(_a , """use_cache""" ): return SCREAMING_SNAKE_CASE__ : Tuple = model_class(_a ).to(_a ) if "use_cache" not in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = model(**_a ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return SCREAMING_SNAKE_CASE__ : Dict = ( getattr(_a , """decoder_layers""" , _a ) or getattr(_a , """num_decoder_layers""" , _a ) or config.num_hidden_layers ) SCREAMING_SNAKE_CASE__ : Dict = getattr(_a , """num_kv_heads""" , config.num_attention_heads ) SCREAMING_SNAKE_CASE__ : Tuple = getattr(_a , """d_model""" , config.hidden_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = embed_dim // num_attention_heads SCREAMING_SNAKE_CASE__ : int = outputs["""past_key_values"""] self.assertEqual(len(_a ) , _a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = inputs["""input_ids"""].shape for i in range(_a ): if config.new_decoder_architecture: SCREAMING_SNAKE_CASE__ : Any = config.num_attention_heads elif config.multi_query: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) SCREAMING_SNAKE_CASE__ : str = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = model.generate(**_a , do_sample=_a , max_new_tokens=19 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.batch_decode(_a )[0] self.assertEqual(_a , _a ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = FalconForCausalLM.from_pretrained(_a ) model.eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**_a , do_sample=_a , max_new_tokens=4 ) model.generate(**_a , do_sample=_a , max_new_tokens=4 ) model.generate(**_a , num_beams=2 , max_new_tokens=4 ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = FalconForCausalLM.from_pretrained(_a ) model.eval() model.to(device=_a ) SCREAMING_SNAKE_CASE__ : str = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(_a ) # Test results are the same with and without cache SCREAMING_SNAKE_CASE__ : str = model.generate(**_a , do_sample=_a , max_new_tokens=20 , use_cache=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate(**_a , do_sample=_a , max_new_tokens=20 , use_cache=_a ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = (DDPMParallelScheduler,) def _a ( self , **_a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> List[str]: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> int: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> List[Any]: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> List[str]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" 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 _a ( self ) -> List[Any]: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : str = 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.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter + 0.1 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter - 0.1 SCREAMING_SNAKE_CASE__ : str = samplea.shape[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(_a )[0:3, None].repeat(1 , _a ) SCREAMING_SNAKE_CASE__ : Any = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE__ : int = scheduler.batch_step_no_noise(_a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 1_153.1_833 ) < 1E-2 assert abs(result_mean.item() - 0.5_005 ) < 1E-3 def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Tuple = len(_a ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : List[str] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample SCREAMING_SNAKE_CASE__ : List[str] = pred_prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Any = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : Any = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : Any = self.dummy_model() SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : List[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample SCREAMING_SNAKE_CASE__ : Optional[int] = pred_prev_sample SCREAMING_SNAKE_CASE__ : int = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : str = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Any = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Dict = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Dict = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : str = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : str = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : Optional[Any] = 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 _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [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 )
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a=None , _a=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = data SCREAMING_SNAKE_CASE__ : Union[str, Any] = previous SCREAMING_SNAKE_CASE__ : Optional[Any] = next_node def __str__( self ) -> str: """simple docstring""" return f'''{self.data}''' def _a ( self ) -> int: """simple docstring""" return self.data def _a ( self ) -> Dict: """simple docstring""" return self.next def _a ( self ) -> Union[str, Any]: """simple docstring""" return self.previous class __a : '''simple docstring''' def __init__( self , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = head def __iter__( self ) -> Tuple: """simple docstring""" return self def _a ( self ) -> List[Any]: """simple docstring""" if not self.current: raise StopIteration else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.current.get_data() SCREAMING_SNAKE_CASE__ : List[Any] = self.current.get_next() return value class __a : '''simple docstring''' def __init__( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = None # First node in list SCREAMING_SNAKE_CASE__ : Tuple = None # Last node in list def __str__( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.head SCREAMING_SNAKE_CASE__ : Optional[int] = [] while current is not None: nodes.append(current.get_data() ) SCREAMING_SNAKE_CASE__ : Dict = current.get_next() return " ".join(str(_a ) for node in nodes ) def __contains__( self , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.head while current: if current.get_data() == value: return True SCREAMING_SNAKE_CASE__ : List[str] = current.get_next() return False def __iter__( self ) -> int: """simple docstring""" return LinkedListIterator(self.head ) def _a ( self ) -> int: """simple docstring""" if self.head: return self.head.get_data() return None def _a ( self ) -> Union[str, Any]: """simple docstring""" if self.tail: return self.tail.get_data() return None def _a ( self , _a ) -> None: """simple docstring""" if self.head is None: SCREAMING_SNAKE_CASE__ : List[Any] = node SCREAMING_SNAKE_CASE__ : str = node else: self.insert_before_node(self.head , _a ) def _a ( self , _a ) -> None: """simple docstring""" if self.head is None: self.set_head(_a ) else: self.insert_after_node(self.tail , _a ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = Node(_a ) if self.head is None: self.set_head(_a ) else: self.set_tail(_a ) def _a ( self , _a , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = node SCREAMING_SNAKE_CASE__ : List[str] = node.previous if node.get_previous() is None: SCREAMING_SNAKE_CASE__ : List[Any] = node_to_insert else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = node_to_insert SCREAMING_SNAKE_CASE__ : Dict = node_to_insert def _a ( self , _a , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = node SCREAMING_SNAKE_CASE__ : Union[str, Any] = node.next if node.get_next() is None: SCREAMING_SNAKE_CASE__ : List[Any] = node_to_insert else: SCREAMING_SNAKE_CASE__ : Optional[int] = node_to_insert SCREAMING_SNAKE_CASE__ : Optional[int] = node_to_insert def _a ( self , _a , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 1 SCREAMING_SNAKE_CASE__ : str = Node(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.head while node: if current_position == position: self.insert_before_node(_a , _a ) return current_position += 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = node.next self.insert_after_node(self.tail , _a ) def _a ( self , _a ) -> Node: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.head while node: if node.get_data() == item: return node SCREAMING_SNAKE_CASE__ : Any = node.get_next() raise Exception("""Node not found""" ) def _a ( self , _a ) -> Optional[int]: """simple docstring""" if (node := self.get_node(_a )) is not None: if node == self.head: SCREAMING_SNAKE_CASE__ : str = self.head.get_next() if node == self.tail: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(_a ) @staticmethod def _a ( _a ) -> None: """simple docstring""" if node.get_next(): SCREAMING_SNAKE_CASE__ : str = node.previous if node.get_previous(): SCREAMING_SNAKE_CASE__ : List[Any] = node.next SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Dict = None def _a ( self ) -> Union[str, Any]: """simple docstring""" return self.head is None def _lowercase ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 a :int = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 2048-bit 14: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AACAA68FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 3072-bit 15: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 4096-bit 16: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + "FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 6144-bit 17: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + "6DCC4024FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 8192-bit 18: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" + "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" + "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" + "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" + "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" + "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" + "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" + "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" + "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" + "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" + "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, } class __a : '''simple docstring''' def __init__( self , _a = 14 ) -> None: """simple docstring""" if group not in primes: raise ValueError("""Unsupported Group""" ) SCREAMING_SNAKE_CASE__ : Dict = primes[group]["""prime"""] SCREAMING_SNAKE_CASE__ : int = primes[group]["""generator"""] SCREAMING_SNAKE_CASE__ : List[str] = int(hexlify(urandom(32 ) ) , base=16 ) def _a ( self ) -> str: """simple docstring""" return hex(self.__private_key )[2:] def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = pow(self.generator , self.__private_key , self.prime ) return hex(_a )[2:] def _a ( self , _a ) -> bool: """simple docstring""" return ( 2 <= key <= self.prime - 2 and pow(_a , (self.prime - 1) // 2 , self.prime ) == 1 ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = int(_a , base=16 ) if not self.is_valid_public_key(_a ): raise ValueError("""Invalid public key""" ) SCREAMING_SNAKE_CASE__ : str = pow(_a , self.__private_key , self.prime ) return shaaaa(str(_a ).encode() ).hexdigest() @staticmethod def _a ( _a , _a ) -> bool: """simple docstring""" return ( 2 <= remote_public_key_str <= prime - 2 and pow(_a , (prime - 1) // 2 , _a ) == 1 ) @staticmethod def _a ( _a , _a , _a = 14 ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = int(_a , base=16 ) SCREAMING_SNAKE_CASE__ : Dict = int(_a , base=16 ) SCREAMING_SNAKE_CASE__ : Tuple = primes[group]["""prime"""] if not DiffieHellman.is_valid_public_key_static(_a , _a ): raise ValueError("""Invalid public key""" ) SCREAMING_SNAKE_CASE__ : Any = pow(_a , _a , _a ) return shaaaa(str(_a ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu a :Any = False class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _a ( self ) -> Optional[Any]: """simple docstring""" return 12 @property def _a ( self ) -> Union[str, Any]: """simple docstring""" return 12 @property def _a ( self ) -> str: """simple docstring""" return 32 @property def _a ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def _a ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(_a ) @property def _a ( self ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = 12 SCREAMING_SNAKE_CASE__ : str = 12 SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """attention_bias""": True, """cross_attention_dim""": 32, """attention_head_dim""": height * width, """num_attention_heads""": 1, """num_vector_embeds""": self.num_embed, """num_embeds_ada_norm""": self.num_embeds_ada_norm, """norm_num_groups""": 32, """sample_size""": width, """activation_fn""": """geglu-approximate""", } SCREAMING_SNAKE_CASE__ : List[str] = TransformeraDModel(**_a ) return model def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """cpu""" SCREAMING_SNAKE_CASE__ : str = self.dummy_vqvae SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : str = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_transformer SCREAMING_SNAKE_CASE__ : Dict = VQDiffusionScheduler(self.num_embed ) SCREAMING_SNAKE_CASE__ : int = LearnedClassifierFreeSamplingEmbeddings(learnable=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = VQDiffusionPipeline( vqvae=_a , text_encoder=_a , tokenizer=_a , transformer=_a , scheduler=_a , learned_classifier_free_sampling_embeddings=_a , ) SCREAMING_SNAKE_CASE__ : str = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Dict = """teddy bear playing in the pool""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe([prompt] , generator=_a , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = pipe( [prompt] , generator=_a , output_type="""np""" , return_dict=_a , num_inference_steps=2 )[0] SCREAMING_SNAKE_CASE__ : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.6_551, 0.6_168, 0.5_008, 0.5_676, 0.5_659, 0.4_295, 0.6_073, 0.5_599, 0.4_992] ) 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 _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = """cpu""" SCREAMING_SNAKE_CASE__ : Any = self.dummy_vqvae SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : Tuple = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_transformer SCREAMING_SNAKE_CASE__ : List[str] = VQDiffusionScheduler(self.num_embed ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = LearnedClassifierFreeSamplingEmbeddings( learnable=_a , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = VQDiffusionPipeline( vqvae=_a , text_encoder=_a , tokenizer=_a , transformer=_a , scheduler=_a , learned_classifier_free_sampling_embeddings=_a , ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """teddy bear playing in the pool""" SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = pipe([prompt] , generator=_a , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ : int = output.images SCREAMING_SNAKE_CASE__ : int = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe( [prompt] , generator=_a , output_type="""np""" , return_dict=_a , num_inference_steps=2 )[0] SCREAMING_SNAKE_CASE__ : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0.6_693, 0.6_075, 0.4_959, 0.5_701, 0.5_583, 0.4_333, 0.6_171, 0.5_684, 0.4_988] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq""" ) SCREAMING_SNAKE_CASE__ : Tuple = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=_a ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = pipeline( """teddy bear playing in the pool""" , num_images_per_prompt=1 , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : str = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING a :int = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , *_a , **_a ) -> str: """simple docstring""" super().__init__(*_a , **_a ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def _a ( self , _a=None , _a=None , _a=None ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {} SCREAMING_SNAKE_CASE__ : Tuple = {} if prompt is not None: SCREAMING_SNAKE_CASE__ : str = prompt if generate_kwargs is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: SCREAMING_SNAKE_CASE__ : Optional[Any] = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) SCREAMING_SNAKE_CASE__ : List[Any] = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _a , **_a ) -> Optional[Any]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = load_image(_a ) if prompt is not None: if not isinstance(_a , _a ): raise ValueError( f'''Received an invalid text input, got - {type(_a )} - but expected a single string. ''' """Note also that one single text can be provided for conditional image to text generation.""" ) SCREAMING_SNAKE_CASE__ : Tuple = self.model.config.model_type if model_type == "git": SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(images=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer(text=_a , add_special_tokens=_a ).input_ids SCREAMING_SNAKE_CASE__ : Dict = [self.tokenizer.cls_token_id] + input_ids SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(_a ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(images=_a , header_text=_a , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(images=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer(_a , return_tensors=self.framework ) model_inputs.update(_a ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor(images=_a , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: SCREAMING_SNAKE_CASE__ : List[str] = None return model_inputs def _a ( self , _a , _a=None ) -> Tuple: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , _a ) and all(x is None for x in model_inputs["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ : Optional[int] = None if generate_kwargs is None: SCREAMING_SNAKE_CASE__ : str = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs.pop(self.model.main_input_name ) SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(_a , **_a , **_a ) return model_outputs def _a ( self , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [] for output_ids in model_outputs: SCREAMING_SNAKE_CASE__ : Any = { """generated_text""": self.tokenizer.decode( _a , skip_special_tokens=_a , ) } records.append(_a ) return records
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint 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." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _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 , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() a :List[str] = logging.get_logger(__name__) a :List[str] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn.grep_linear": "encoder.layers.*.attention.gru_rel_pos_linear", "self_attn.relative_attention_bias": "encoder.layers.*.attention.rel_attn_embed", "self_attn.grep_a": "encoder.layers.*.attention.gru_rel_pos_const", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "ctc_proj", "mask_emb": "masked_spec_embed", } a :str = [ "ctc_proj", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: for attribute in key.split(""".""" ): SCREAMING_SNAKE_CASE__ : Dict = getattr(__lowerCAmelCase , __lowerCAmelCase ) if weight_type is not None: SCREAMING_SNAKE_CASE__ : List[str] = getattr(__lowerCAmelCase , __lowerCAmelCase ).shape else: SCREAMING_SNAKE_CASE__ : Any = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE__ : str = value else: SCREAMING_SNAKE_CASE__ : Dict = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : int = fairseq_model.state_dict() SCREAMING_SNAKE_CASE__ : Union[str, Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE__ : Any = False if "conv_layers" in name: load_conv_layer( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , hf_model.config.feat_extract_norm == """group""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True if "*" in mapped_key: SCREAMING_SNAKE_CASE__ : int = name.split(__lowerCAmelCase )[0].split(""".""" )[-2] SCREAMING_SNAKE_CASE__ : Any = mapped_key.replace("""*""" , __lowerCAmelCase ) if "weight_g" in name: SCREAMING_SNAKE_CASE__ : List[str] = """weight_g""" elif "weight_v" in name: SCREAMING_SNAKE_CASE__ : Dict = """weight_v""" elif "bias" in name and "relative_attention_bias" not in name: SCREAMING_SNAKE_CASE__ : Any = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE__ : List[Any] = """weight""" else: SCREAMING_SNAKE_CASE__ : Dict = None set_recursively(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) continue if not is_used: unused_weights.append(__lowerCAmelCase ) logger.warning(F'''Unused weights: {unused_weights}''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = full_name.split("""conv_layers.""" )[-1] SCREAMING_SNAKE_CASE__ : int = name.split(""".""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(items[0] ) SCREAMING_SNAKE_CASE__ : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : List[Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : str = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) SCREAMING_SNAKE_CASE__ : Optional[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE__ : Tuple = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__lowerCAmelCase ) @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None ) -> List[str]: # load the pre-trained checkpoints SCREAMING_SNAKE_CASE__ : List[str] = torch.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = WavLMConfigOrig(checkpoint["""cfg"""] ) SCREAMING_SNAKE_CASE__ : Tuple = WavLMOrig(__lowerCAmelCase ) model.load_state_dict(checkpoint["""model"""] ) model.eval() if config_path is not None: SCREAMING_SNAKE_CASE__ : int = WavLMConfig.from_pretrained(__lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__ : List[str] = WavLMConfig() SCREAMING_SNAKE_CASE__ : Any = WavLMModel(__lowerCAmelCase ) recursively_load_weights(__lowerCAmelCase , __lowerCAmelCase ) hf_wavlm.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": a :str = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") a :List[Any] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 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 if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> float: if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :Union[str, Any] = logging.get_logger(__name__) a :Tuple = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = """mgp-str""" def __init__( self , _a=[32, 128] , _a=4 , _a=3 , _a=27 , _a=38 , _a=50_257 , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=4.0 , _a=True , _a=False , _a=1E-5 , _a=0.0 , _a=0.0 , _a=0.0 , _a=False , _a=0.02 , **_a , ) -> List[str]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : str = num_channels SCREAMING_SNAKE_CASE__ : Any = max_token_length SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_character_labels SCREAMING_SNAKE_CASE__ : Tuple = num_bpe_labels SCREAMING_SNAKE_CASE__ : Optional[int] = num_wordpiece_labels SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = mlp_ratio SCREAMING_SNAKE_CASE__ : Dict = distilled SCREAMING_SNAKE_CASE__ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = drop_rate SCREAMING_SNAKE_CASE__ : Any = qkv_bias SCREAMING_SNAKE_CASE__ : Tuple = attn_drop_rate SCREAMING_SNAKE_CASE__ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE__ : int = output_aa_attentions SCREAMING_SNAKE_CASE__ : int = initializer_range
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a=0.01 , _a=1_000 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = p_stop SCREAMING_SNAKE_CASE__ : str = max_length def __iter__( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = False while not stop and count < self.max_length: yield count count += 1 SCREAMING_SNAKE_CASE__ : List[Any] = random.random() < self.p_stop class __a (unittest.TestCase): '''simple docstring''' def _a ( self , _a , _a , _a=False , _a=True ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [ BatchSamplerShard(_a , 2 , _a , split_batches=_a , even_batches=_a ) for i in range(2 ) ] SCREAMING_SNAKE_CASE__ : Any = [list(_a ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(_a ) for shard in batch_sampler_shards] , [len(_a ) for e in expected] ) self.assertListEqual(_a , _a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(_a , _a ) SCREAMING_SNAKE_CASE__ : int = BatchSampler(range(24 ) , batch_size=3 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = BatchSampler(range(21 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(22 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(_a , _a ) SCREAMING_SNAKE_CASE__ : Any = BatchSampler(range(22 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ : Any = BatchSampler(range(20 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(_a , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(_a , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = [[], []] self.check_batch_sampler_shards(_a , _a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BatchSampler(range(24 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) SCREAMING_SNAKE_CASE__ : Dict = BatchSampler(range(24 ) , batch_size=4 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size. SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchSampler(range(22 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(22 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Dict = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. SCREAMING_SNAKE_CASE__ : int = BatchSampler(range(21 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) SCREAMING_SNAKE_CASE__ : Dict = BatchSampler(range(21 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ : str = BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : str = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [[], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. SCREAMING_SNAKE_CASE__ : Tuple = BatchSampler(range(21 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(22 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(22 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchSampler(range(20 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ : Any = BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[[0, 1]], []] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : Any = BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Dict = [[], []] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BatchSampler(range(24 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = BatchSampler(range(24 ) , batch_size=4 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size. SCREAMING_SNAKE_CASE__ : Tuple = BatchSampler(range(22 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : Dict = BatchSampler(range(22 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. SCREAMING_SNAKE_CASE__ : Tuple = BatchSampler(range(21 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(21 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ : Optional[int] = BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [[[0, 1]], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) SCREAMING_SNAKE_CASE__ : List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : Dict = [[], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] SCREAMING_SNAKE_CASE__ : Tuple = [BatchSamplerShard(_a , 2 , _a , even_batches=_a ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def _a ( self , _a , _a , _a , _a=False , _a=2 , _a=False ) -> Optional[int]: """simple docstring""" random.seed(_a ) SCREAMING_SNAKE_CASE__ : int = list(_a ) SCREAMING_SNAKE_CASE__ : Dict = [ IterableDatasetShard( _a , batch_size=_a , drop_last=_a , num_processes=_a , process_index=_a , split_batches=_a , ) for i in range(_a ) ] SCREAMING_SNAKE_CASE__ : Any = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(_a ) iterable_dataset_lists.append(list(_a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size SCREAMING_SNAKE_CASE__ : int = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(_a ) , len(_a ) ) self.assertTrue(len(_a ) % shard_batch_size == 0 ) SCREAMING_SNAKE_CASE__ : Any = [] for idx in range(0 , len(_a ) , _a ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(_a ) < len(_a ): reference += reference self.assertListEqual(_a , reference[: len(_a )] ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 42 SCREAMING_SNAKE_CASE__ : List[str] = RandomIterableDataset() self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) # Edge case with a very small dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BatchSampler(range(16 ) , batch_size=4 , drop_last=_a ) SCREAMING_SNAKE_CASE__ : List[str] = SkipBatchSampler(_a , 2 ) self.assertListEqual(list(_a ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = DataLoader(list(range(16 ) ) , batch_size=4 ) SCREAMING_SNAKE_CASE__ : Any = skip_first_batches(_a , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def _a ( self ) -> Dict: """simple docstring""" Accelerator() SCREAMING_SNAKE_CASE__ : Tuple = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" # flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter a :List[Any] = logging.get_logger(__name__) a :Dict[Optional[str], Type[Formatter]] = {} a :Dict[Optional[str], str] = {} a :Dict[Optional[str], Exception] = {} def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Any = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( F'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})''' ) SCREAMING_SNAKE_CASE__ : Dict = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( F'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})''' ) SCREAMING_SNAKE_CASE__ : int = format_type def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): SCREAMING_SNAKE_CASE__ : Any = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=["python"]) _register_formatter(ArrowFormatter, "arrow", aliases=["pa", "pyarrow"]) _register_formatter(NumpyFormatter, "numpy", aliases=["np"]) _register_formatter(PandasFormatter, "pandas", aliases=["pd"]) _register_formatter(CustomFormatter, "custom") if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, "torch", aliases=["pt", "pytorch"]) else: a :List[Any] = ValueError("PyTorch needs to be installed to be able to return PyTorch tensors.") _register_unavailable_formatter(_torch_error, "torch", aliases=["pt", "pytorch"]) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, "tensorflow", aliases=["tf"]) else: a :Tuple = ValueError("Tensorflow needs to be installed to be able to return Tensorflow tensors.") _register_unavailable_formatter(_tf_error, "tensorflow", aliases=["tf"]) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, "jax", aliases=[]) else: a :Optional[int] = ValueError("JAX needs to be installed to be able to return JAX arrays.") _register_unavailable_formatter(_jax_error, "jax", aliases=[]) def _lowercase ( __lowerCAmelCase ) -> Optional[str]: if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def _lowercase ( __lowerCAmelCase , **__lowerCAmelCase ) -> Formatter: SCREAMING_SNAKE_CASE__ : List[Any] = get_format_type_from_alias(__lowerCAmelCase ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**__lowerCAmelCase ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( F'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'''' )
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = n SCREAMING_SNAKE_CASE__ : int = [None] * self.n SCREAMING_SNAKE_CASE__ : str = 0 # index of the first element SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : Tuple = 0 def __len__( self ) -> int: """simple docstring""" return self.size def _a ( self ) -> bool: """simple docstring""" return self.size == 0 def _a ( self ) -> Any: """simple docstring""" return False if self.is_empty() else self.array[self.front] def _a ( self , _a ) -> int: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) SCREAMING_SNAKE_CASE__ : Tuple = data SCREAMING_SNAKE_CASE__ : int = (self.rear + 1) % self.n self.size += 1 return self def _a ( self ) -> Dict: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) SCREAMING_SNAKE_CASE__ : Dict = self.array[self.front] SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Dict = (self.front + 1) % self.n self.size -= 1 return temp
680
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 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": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def _lowercase ( __lowerCAmelCase ) -> Tuple: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def _lowercase ( ) -> str: with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" SCREAMING_SNAKE_CASE__ : List[Any] = [1, 2, 3] with pytest.raises(__lowerCAmelCase ): with parallel_backend("""unsupported backend""" ): map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=2 ) with pytest.raises(__lowerCAmelCase ): with parallel_backend("""unsupported backend""" ): map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" , [2, -1] ) def _lowercase ( __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [1, 2] SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""a""": 1, """b""": 2} SCREAMING_SNAKE_CASE__ : List[str] = {"""a""": [1, 2], """b""": [3, 4]} SCREAMING_SNAKE_CASE__ : int = {"""a""": {"""1""": 1}, """b""": 2} SCREAMING_SNAKE_CASE__ : List[str] = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} SCREAMING_SNAKE_CASE__ : List[Any] = [2, 3] SCREAMING_SNAKE_CASE__ : List[Any] = {"""a""": 2, """b""": 3} SCREAMING_SNAKE_CASE__ : Optional[int] = {"""a""": [2, 3], """b""": [4, 5]} SCREAMING_SNAKE_CASE__ : List[Any] = {"""a""": {"""1""": 2}, """b""": 3} SCREAMING_SNAKE_CASE__ : List[Any] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = KandinskyVaaControlnetPipeline _SCREAMING_SNAKE_CASE :Optional[int] = ["""image_embeds""", """negative_image_embeds""", """hint"""] _SCREAMING_SNAKE_CASE :List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] _SCREAMING_SNAKE_CASE :List[str] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _SCREAMING_SNAKE_CASE :List[Any] = False @property def _a ( self ) -> List[Any]: """simple docstring""" return 32 @property def _a ( self ) -> Optional[Any]: """simple docstring""" return 32 @property def _a ( self ) -> List[str]: """simple docstring""" return self.time_input_dim @property def _a ( self ) -> Optional[int]: """simple docstring""" return self.time_input_dim * 4 @property def _a ( self ) -> str: """simple docstring""" return 100 @property def _a ( self ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } SCREAMING_SNAKE_CASE__ : Any = UNetaDConditionModel(**_a ) return model @property def _a ( self ) -> str: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _a ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = VQModel(**self.dummy_movq_kwargs ) return model def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.dummy_unet SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_movq SCREAMING_SNAKE_CASE__ : int = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=_a , set_alpha_to_one=_a , steps_offset=1 , prediction_type="""epsilon""" , thresholding=_a , ) SCREAMING_SNAKE_CASE__ : List[Any] = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def _a ( self , _a , _a=0 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _a ) # create hint SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(_a ) ).to(_a ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : Dict = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Any = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """cpu""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Tuple = self.pipeline_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Tuple = pipe(**self.get_dummy_inputs(_a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : Any = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] SCREAMING_SNAKE_CASE__ : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.from_numpy(np.array(_a ) ).float() / 255.0 SCREAMING_SNAKE_CASE__ : str = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Any = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_a ) SCREAMING_SNAKE_CASE__ : str = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : List[str] = """A robot, 4k photo""" SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device="""cuda""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device="""cuda""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = pipeline( image_embeds=_a , negative_image_embeds=_a , hint=_a , generator=_a , num_inference_steps=100 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_a , _a )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Optional[int] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Any = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys a :Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(">=", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType a :Optional[Any] = get_logger(__name__) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Optional[int]: os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) with FSDP.state_dict_type( __lowerCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE__ : int = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE__ : Optional[Any] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if accelerator.process_index == 0: logger.info(F'''Saving model to {output_model_file}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE__ : Optional[int] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Saving model to {output_model_file}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE__ : str = os.path.join(__lowerCAmelCase , F'''{MODEL_NAME}_{model_index}''' ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) logger.info(F'''Saving model to {ckpt_dir}''' ) SCREAMING_SNAKE_CASE__ : Any = {"""model""": state_dict} dist_cp.save_state_dict( state_dict=__lowerCAmelCase , storage_writer=dist_cp.FileSystemWriter(__lowerCAmelCase ) , planner=DefaultSavePlanner() , ) logger.info(F'''Model saved to {ckpt_dir}''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Dict: accelerator.wait_for_everyone() with FSDP.state_dict_type( __lowerCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(__lowerCAmelCase ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( """Set the `sync_module_states` flag to `True` so that model states are synced across processes when """ """initializing FSDP object""" ) return SCREAMING_SNAKE_CASE__ : Union[str, Any] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Loading model from {input_model_file}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE__ : Optional[int] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Loading model from {input_model_file}''' ) SCREAMING_SNAKE_CASE__ : Any = torch.load(__lowerCAmelCase ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE__ : Tuple = ( os.path.join(__lowerCAmelCase , F'''{MODEL_NAME}_{model_index}''' ) if F'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading model from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""model""": model.state_dict()} dist_cp.load_state_dict( state_dict=__lowerCAmelCase , storage_reader=dist_cp.FileSystemReader(__lowerCAmelCase ) , planner=DefaultLoadPlanner() , ) SCREAMING_SNAKE_CASE__ : Dict = state_dict["""model"""] logger.info(F'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> int: os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) with FSDP.state_dict_type( __lowerCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE__ : str = FSDP.optim_state_dict(__lowerCAmelCase , __lowerCAmelCase ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: SCREAMING_SNAKE_CASE__ : List[Any] = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Optimizer state saved in {output_optimizer_file}''' ) else: SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) logger.info(F'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={"""optimizer""": optim_state} , storage_writer=dist_cp.FileSystemWriter(__lowerCAmelCase ) , planner=DefaultSavePlanner() , ) logger.info(F'''Optimizer state saved in {ckpt_dir}''' ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Optional[Any]: accelerator.wait_for_everyone() with FSDP.state_dict_type( __lowerCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE__ : str = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: SCREAMING_SNAKE_CASE__ : int = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) logger.info(F'''Loading Optimizer state from {input_optimizer_file}''' ) SCREAMING_SNAKE_CASE__ : str = torch.load(__lowerCAmelCase ) logger.info(F'''Optimizer state loaded from {input_optimizer_file}''' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = ( os.path.join(__lowerCAmelCase , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if F'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading Optimizer from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE__ : int = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="""optimizer""" , storage_reader=dist_cp.FileSystemReader(__lowerCAmelCase ) , ) SCREAMING_SNAKE_CASE__ : Tuple = optim_state["""optimizer"""] logger.info(F'''Optimizer loaded from {ckpt_dir}''' ) SCREAMING_SNAKE_CASE__ : Any = FSDP.optim_state_dict_to_load(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) optimizer.load_state_dict(__lowerCAmelCase )
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = """dandelin/vilt-b32-finetuned-vqa""" _SCREAMING_SNAKE_CASE :Union[str, Any] = ( """This is a tool that answers a question about an image. It takes an input named `image` which should be the """ """image containing the information, as well as a `question` which should be the question in English. It """ """returns a text that is the answer to the question.""" ) _SCREAMING_SNAKE_CASE :Dict = """image_qa""" _SCREAMING_SNAKE_CASE :str = AutoProcessor _SCREAMING_SNAKE_CASE :Optional[Any] = AutoModelForVisualQuestionAnswering _SCREAMING_SNAKE_CASE :List[Any] = ["""image""", """text"""] _SCREAMING_SNAKE_CASE :List[str] = ["""text"""] def __init__( self , *_a , **_a ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""vision"""] ) super().__init__(*_a , **_a ) def _a ( self , _a , _a ) -> Tuple: """simple docstring""" return self.pre_processor(_a , _a , return_tensors="""pt""" ) def _a ( self , _a ) -> List[str]: """simple docstring""" with torch.no_grad(): return self.model(**_a ).logits def _a ( self , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" from math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" SCREAMING_SNAKE_CASE__ : str = True # 0 and 1 are none primes. if number <= 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = False for divisor in range(2 , int(round(sqrt(__lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: SCREAMING_SNAKE_CASE__ : Dict = False break # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'status' must been from type bool" return status def _lowercase ( __lowerCAmelCase ) -> Optional[Any]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N SCREAMING_SNAKE_CASE__ : Optional[Any] = list(range(2 , n + 1 ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(__lowerCAmelCase ) ): for j in range(i + 1 , len(__lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): SCREAMING_SNAKE_CASE__ : int = 0 # filters actual prime numbers. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [x for x in begin_list if x != 0] # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def _lowercase ( __lowerCAmelCase ) -> str: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" SCREAMING_SNAKE_CASE__ : Any = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(__lowerCAmelCase ): ans.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def _lowercase ( __lowerCAmelCase ) -> int: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" SCREAMING_SNAKE_CASE__ : List[str] = [] # this list will be returns of the function. # potential prime number factors. SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Tuple = number if number == 0 or number == 1: ans.append(__lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(__lowerCAmelCase ): while quotient != 1: if is_prime(__lowerCAmelCase ) and (quotient % factor == 0): ans.append(__lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def _lowercase ( __lowerCAmelCase ) -> Any: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE__ : List[Any] = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE__ : Dict = prime_factorization(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = max(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type int" return ans def _lowercase ( __lowerCAmelCase ) -> List[Any]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE__ : Optional[int] = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE__ : Optional[int] = prime_factorization(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type int" return ans def _lowercase ( __lowerCAmelCase ) -> Dict: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , __lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def _lowercase ( __lowerCAmelCase ) -> Optional[int]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , __lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def _lowercase ( __lowerCAmelCase ) -> str: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (number > 2) and is_even(__lowerCAmelCase ) ), "'number' must been an int, even and > 2" SCREAMING_SNAKE_CASE__ : List[Any] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' SCREAMING_SNAKE_CASE__ : str = get_prime_numbers(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) # run variable for while-loops. SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = None # exit variable. for break up the loops SCREAMING_SNAKE_CASE__ : List[Any] = True while i < len_pn and loop: SCREAMING_SNAKE_CASE__ : Tuple = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: SCREAMING_SNAKE_CASE__ : List[Any] = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (len(__lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE__ : int = 0 while numbera != 0: SCREAMING_SNAKE_CASE__ : List[str] = numbera % numbera SCREAMING_SNAKE_CASE__ : str = numbera SCREAMING_SNAKE_CASE__ : Union[str, Any] = rest # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE__ : Optional[int] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' SCREAMING_SNAKE_CASE__ : Optional[int] = prime_factorization(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prime_factorization(__lowerCAmelCase ) elif numbera == 1 or numbera == 1: SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : Tuple = [] SCREAMING_SNAKE_CASE__ : str = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : List[Any] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: SCREAMING_SNAKE_CASE__ : Union[str, Any] = prime_fac_a.count(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = prime_fac_a.count(__lowerCAmelCase ) for _ in range(max(__lowerCAmelCase , __lowerCAmelCase ) ): ans *= n else: SCREAMING_SNAKE_CASE__ : Any = prime_fac_a.count(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ): ans *= n done.append(__lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: SCREAMING_SNAKE_CASE__ : Any = prime_fac_a.count(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ): ans *= n done.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def _lowercase ( __lowerCAmelCase ) -> int: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : List[str] = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(__lowerCAmelCase ): ans += 1 # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and is_prime( __lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: assert ( is_prime(__lowerCAmelCase ) and is_prime(__lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" SCREAMING_SNAKE_CASE__ : Dict = p_number_a + 1 # jump to the next number SCREAMING_SNAKE_CASE__ : Any = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(__lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(__lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(__lowerCAmelCase ): number += 1 # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ans[0] != p_number_a and ans[len(__lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def _lowercase ( __lowerCAmelCase ) -> str: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" SCREAMING_SNAKE_CASE__ : str = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(__lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(__lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def _lowercase ( __lowerCAmelCase ) -> Optional[int]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_divisors(__lowerCAmelCase ) # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(__lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. SCREAMING_SNAKE_CASE__ : int = gcd(abs(__lowerCAmelCase ) , abs(__lowerCAmelCase ) ) # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def _lowercase ( __lowerCAmelCase ) -> Any: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" SCREAMING_SNAKE_CASE__ : List[Any] = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def _lowercase ( __lowerCAmelCase ) -> List[str]: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : List[str] = 1 # this will be return for _ in range(n - 1 ): SCREAMING_SNAKE_CASE__ : str = ans ans += fiba SCREAMING_SNAKE_CASE__ : Tuple = tmp return ans
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> list[list]: SCREAMING_SNAKE_CASE__ : Any = current_set.copy() for row_index, row in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = row[0] for column_index, column in enumerate(__lowerCAmelCase ): if magnitude == 0: SCREAMING_SNAKE_CASE__ : int = column continue SCREAMING_SNAKE_CASE__ : Any = column / magnitude # Subtract to cancel term SCREAMING_SNAKE_CASE__ : Union[str, Any] = current_set[0] SCREAMING_SNAKE_CASE__ : Tuple = [first_row] SCREAMING_SNAKE_CASE__ : int = current_set[1::] for row in current_set: SCREAMING_SNAKE_CASE__ : List[str] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__lowerCAmelCase ) continue for column_index in range(len(__lowerCAmelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__lowerCAmelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: SCREAMING_SNAKE_CASE__ : Union[str, Any] = final_set[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) SCREAMING_SNAKE_CASE__ : Any = simplify(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = resultant return final_set def _lowercase ( __lowerCAmelCase ) -> list: if len(__lowerCAmelCase ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) SCREAMING_SNAKE_CASE__ : List[str] = len(__lowerCAmelCase ) + 1 if any(len(__lowerCAmelCase ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(__lowerCAmelCase , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(__lowerCAmelCase ) == 1: return [equations[0][-1] / equations[0][0]] SCREAMING_SNAKE_CASE__ : str = equations.copy() if any(0 in row for row in data_set ): SCREAMING_SNAKE_CASE__ : List[Any] = data_set.copy() SCREAMING_SNAKE_CASE__ : Dict = [] for row_index, row in enumerate(__lowerCAmelCase ): if 0 not in row: SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_set.pop(__lowerCAmelCase ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = data_set.copy() SCREAMING_SNAKE_CASE__ : Optional[Any] = simplify(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = simplified[::-1] SCREAMING_SNAKE_CASE__ : list = [] for row in simplified: SCREAMING_SNAKE_CASE__ : str = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue SCREAMING_SNAKE_CASE__ : List[str] = row.copy()[: len(__lowerCAmelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__lowerCAmelCase ) == 0: solutions.append(0 ) continue SCREAMING_SNAKE_CASE__ : Dict = temp_row[1::] SCREAMING_SNAKE_CASE__ : List[str] = temp_row[::-1] for column_index, column in enumerate(__lowerCAmelCase ): current_solution -= column * solutions[column_index] solutions.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = [] for item in solutions: final.append(float(round(__lowerCAmelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() a :Any = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) a :List[str] = logging.get_logger(__name__) a :Optional[int] = OrderedDict( [ ("align", "EfficientNetImageProcessor"), ("beit", "BeitImageProcessor"), ("bit", "BitImageProcessor"), ("blip", "BlipImageProcessor"), ("blip-2", "BlipImageProcessor"), ("bridgetower", "BridgeTowerImageProcessor"), ("chinese_clip", "ChineseCLIPImageProcessor"), ("clip", "CLIPImageProcessor"), ("clipseg", "ViTImageProcessor"), ("conditional_detr", "ConditionalDetrImageProcessor"), ("convnext", "ConvNextImageProcessor"), ("convnextv2", "ConvNextImageProcessor"), ("cvt", "ConvNextImageProcessor"), ("data2vec-vision", "BeitImageProcessor"), ("deformable_detr", "DeformableDetrImageProcessor"), ("deit", "DeiTImageProcessor"), ("deta", "DetaImageProcessor"), ("detr", "DetrImageProcessor"), ("dinat", "ViTImageProcessor"), ("donut-swin", "DonutImageProcessor"), ("dpt", "DPTImageProcessor"), ("efficientformer", "EfficientFormerImageProcessor"), ("efficientnet", "EfficientNetImageProcessor"), ("flava", "FlavaImageProcessor"), ("focalnet", "BitImageProcessor"), ("git", "CLIPImageProcessor"), ("glpn", "GLPNImageProcessor"), ("groupvit", "CLIPImageProcessor"), ("imagegpt", "ImageGPTImageProcessor"), ("instructblip", "BlipImageProcessor"), ("layoutlmv2", "LayoutLMv2ImageProcessor"), ("layoutlmv3", "LayoutLMv3ImageProcessor"), ("levit", "LevitImageProcessor"), ("mask2former", "Mask2FormerImageProcessor"), ("maskformer", "MaskFormerImageProcessor"), ("mgp-str", "ViTImageProcessor"), ("mobilenet_v1", "MobileNetV1ImageProcessor"), ("mobilenet_v2", "MobileNetV2ImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevitv2", "MobileViTImageProcessor"), ("nat", "ViTImageProcessor"), ("oneformer", "OneFormerImageProcessor"), ("owlvit", "OwlViTImageProcessor"), ("perceiver", "PerceiverImageProcessor"), ("pix2struct", "Pix2StructImageProcessor"), ("poolformer", "PoolFormerImageProcessor"), ("regnet", "ConvNextImageProcessor"), ("resnet", "ConvNextImageProcessor"), ("sam", "SamImageProcessor"), ("segformer", "SegformerImageProcessor"), ("swiftformer", "ViTImageProcessor"), ("swin", "ViTImageProcessor"), ("swin2sr", "Swin2SRImageProcessor"), ("swinv2", "ViTImageProcessor"), ("table-transformer", "DetrImageProcessor"), ("timesformer", "VideoMAEImageProcessor"), ("tvlt", "TvltImageProcessor"), ("upernet", "SegformerImageProcessor"), ("van", "ConvNextImageProcessor"), ("videomae", "VideoMAEImageProcessor"), ("vilt", "ViltImageProcessor"), ("vit", "ViTImageProcessor"), ("vit_hybrid", "ViTHybridImageProcessor"), ("vit_mae", "ViTImageProcessor"), ("vit_msn", "ViTImageProcessor"), ("xclip", "CLIPImageProcessor"), ("yolos", "YolosImageProcessor"), ] ) a :str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _lowercase ( __lowerCAmelCase ) -> int: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: SCREAMING_SNAKE_CASE__ : Dict = model_type_to_module_name(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = importlib.import_module(F'''.{module_name}''' , """transformers.models""" ) try: return getattr(__lowerCAmelCase , __lowerCAmelCase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(__lowerCAmelCase , """__name__""" , __lowerCAmelCase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. SCREAMING_SNAKE_CASE__ : Any = importlib.import_module("""transformers""" ) if hasattr(__lowerCAmelCase , __lowerCAmelCase ): return getattr(__lowerCAmelCase , __lowerCAmelCase ) return None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = False , __lowerCAmelCase = False , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = False , **__lowerCAmelCase , ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_file_from_repo( __lowerCAmelCase , __lowerCAmelCase , cache_dir=__lowerCAmelCase , force_download=__lowerCAmelCase , resume_download=__lowerCAmelCase , proxies=__lowerCAmelCase , use_auth_token=__lowerCAmelCase , revision=__lowerCAmelCase , local_files_only=__lowerCAmelCase , ) if resolved_config_file is None: logger.info( """Could not locate the image processor configuration file, will try to use the model config instead.""" ) return {} with open(__lowerCAmelCase , encoding="""utf-8""" ) as reader: return json.load(__lowerCAmelCase ) class __a : '''simple docstring''' def __init__( self ) -> Optional[Any]: """simple docstring""" raise EnvironmentError( """AutoImageProcessor is designed to be instantiated """ """using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.""" ) @classmethod @replace_list_option_in_docstrings(_a ) def _a ( cls , _a , **_a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = kwargs.pop("""config""" , _a ) SCREAMING_SNAKE_CASE__ : List[Any] = kwargs.pop("""trust_remote_code""" , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = ImageProcessingMixin.get_image_processor_dict(_a , **_a ) SCREAMING_SNAKE_CASE__ : List[Any] = config_dict.get("""image_processor_type""" , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if "AutoImageProcessor" in config_dict.get("""auto_map""" , {} ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = config_dict["""auto_map"""]["""AutoImageProcessor"""] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: SCREAMING_SNAKE_CASE__ : List[str] = config_dict.pop("""feature_extractor_type""" , _a ) if feature_extractor_class is not None: logger.warning( """Could not find image processor class in the image processor config or the model config. Loading""" """ based on pattern matching with the model's feature extractor configuration.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor_class.replace("""FeatureExtractor""" , """ImageProcessor""" ) if "AutoFeatureExtractor" in config_dict.get("""auto_map""" , {} ): SCREAMING_SNAKE_CASE__ : Optional[int] = config_dict["""auto_map"""]["""AutoFeatureExtractor"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feature_extractor_auto_map.replace("""FeatureExtractor""" , """ImageProcessor""" ) logger.warning( """Could not find image processor auto map in the image processor config or the model config.""" """ Loading based on pattern matching with the model's feature extractor configuration.""" ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(_a , _a ): SCREAMING_SNAKE_CASE__ : str = AutoConfig.from_pretrained(_a , **_a ) # It could be in `config.image_processor_type`` SCREAMING_SNAKE_CASE__ : List[Any] = getattr(_a , """image_processor_type""" , _a ) if hasattr(_a , """auto_map""" ) and "AutoImageProcessor" in config.auto_map: SCREAMING_SNAKE_CASE__ : Dict = config.auto_map["""AutoImageProcessor"""] if image_processor_class is not None: SCREAMING_SNAKE_CASE__ : Any = image_processor_class_from_name(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor_auto_map is not None SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor_class is not None or type(_a ) in IMAGE_PROCESSOR_MAPPING SCREAMING_SNAKE_CASE__ : int = resolve_trust_remote_code( _a , _a , _a , _a ) if has_remote_code and trust_remote_code: SCREAMING_SNAKE_CASE__ : Optional[int] = get_class_from_dynamic_module( _a , _a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("""code_revision""" , _a ) if os.path.isdir(_a ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(_a , **_a ) elif image_processor_class is not None: return image_processor_class.from_dict(_a , **_a ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(_a ) in IMAGE_PROCESSOR_MAPPING: SCREAMING_SNAKE_CASE__ : Tuple = IMAGE_PROCESSOR_MAPPING[type(_a )] return image_processor_class.from_dict(_a , **_a ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def _a ( _a , _a ) -> str: """simple docstring""" IMAGE_PROCESSOR_MAPPING.register(_a , _a )
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a :Union[str, Any] = logging.get_logger(__name__) a :int = {"vocab_file": "sentencepiece.bpe.model"} a :Optional[int] = { "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", } } a :Optional[Any] = { "camembert-base": 512, } a :Tuple = "▁" class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""input_ids""", """attention_mask"""] def __init__( self , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=["<s>NOTUSED", "</s>NOTUSED"] , _a = None , **_a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) SCREAMING_SNAKE_CASE__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) SCREAMING_SNAKE_CASE__ : Any = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""<s>NOTUSED""": 0, """<pad>""": 1, """</s>NOTUSED""": 2, """<unk>""": 3} SCREAMING_SNAKE_CASE__ : str = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : Any = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , _a , _a = None , _a = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> List[str]: """simple docstring""" return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , _a ) -> List[str]: """simple docstring""" return self.sp_model.encode(_a , out_type=_a ) def _a ( self , _a ) -> Tuple: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_a ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_a ) def _a ( self , _a ) -> Dict: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : Optional[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : str = [] else: current_sub_tokens.append(_a ) SCREAMING_SNAKE_CASE__ : List[str] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def __getstate__( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Tuple = None return state def __setstate__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : Dict = {} SCREAMING_SNAKE_CASE__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor a :int = logging.get_logger(__name__) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , *_a , **_a ) -> None: """simple docstring""" warnings.warn( """The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use YolosImageProcessor instead.""" , _a , ) super().__init__(*_a , **_a )
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: # Initialise PyTorch model SCREAMING_SNAKE_CASE__ : Optional[Any] = BertConfig.from_json_file(__lowerCAmelCase ) print(F'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ : int = BertForPreTraining(__lowerCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , __lowerCAmelCase ) if __name__ == "__main__": a :Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--bert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT 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." ) a :str = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from manim import * class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE__ : Tuple = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : int = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Tuple = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[str] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : int = VGroup(_a , _a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : List[str] = Text("""CPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Tuple = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE__ : Optional[int] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Text("""GPU""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Any = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.move_to([-1, -1, 0] ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Tuple = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : str = Text("""Model""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : int = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.add(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [] for i, rect in enumerate(_a ): rect.set_stroke(_a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE__ : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=_a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=_a , buff=0.0 ) self.add(_a ) cpu_targs.append(_a ) SCREAMING_SNAKE_CASE__ : Tuple = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Optional[Any] = VGroup(*_a ).arrange(_a , buff=0 ) SCREAMING_SNAKE_CASE__ : Any = Text("""Loaded Checkpoint""" , font_size=24 ) SCREAMING_SNAKE_CASE__ : Tuple = Group(_a , _a ).arrange(_a , aligned_edge=_a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE__ : Any = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE__ : List[str] = MarkupText( f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = MarkupText( f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE__ : Any = MarkupText( f'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a ) , Write(_a ) ) self.play(Write(_a , run_time=1 ) , Create(_a , run_time=1 ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for i, rect in enumerate(_a ): SCREAMING_SNAKE_CASE__ : List[str] = fill.copy().set_fill(_a , opacity=0.7 ) target.move_to(_a ) first_animations.append(GrowFromCenter(_a , run_time=1 ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(_a , run_time=1.5 ) ) self.play(*_a ) self.play(*_a ) self.wait()
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , ) -> Optional[int]: if attention_mask is None: SCREAMING_SNAKE_CASE__ : int = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : str = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=__lowerCAmelCase ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Dict = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=__lowerCAmelCase ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=__lowerCAmelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=16 , _a=2 , _a=4 , _a=4 , _a="relu" , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.0 , _a=20 , _a=2 , _a=1 , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[Any] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : List[Any] = decoder_layerdrop SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = eos_token_id SCREAMING_SNAKE_CASE__ : str = pad_token_id SCREAMING_SNAKE_CASE__ : List[str] = bos_token_id def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = self.eos_token_id # Eos Token SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 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 SCREAMING_SNAKE_CASE__ : Dict = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : List[Any] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() SCREAMING_SNAKE_CASE__ : Dict = prepare_mam_aaa_inputs_dict(_a , _a , _a ) return config, inputs_dict def _a ( self ) -> Optional[int]: """simple docstring""" return MaMaaaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MaMaaaModel(config=_a ).get_decoder().to(_a ).eval() SCREAMING_SNAKE_CASE__ : str = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["""attention_mask"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = inputs_dict["""head_mask"""] # first forward pass SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , attention_mask=_a , head_mask=_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , attention_mask=_a , past_key_values=_a )[ """last_hidden_state""" ] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = 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-2 ) ) def _a ( self , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = MaMaaaModel(config=_a ).to(_a ).eval() SCREAMING_SNAKE_CASE__ : List[str] = model(**_a ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_last_hidden_state SCREAMING_SNAKE_CASE__ : List[Any] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.get_encoder() encoder.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : int = MaMaaaEncoder.from_pretrained(_a ).to(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = encoder(inputs_dict["""input_ids"""] , attention_mask=inputs_dict["""attention_mask"""] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Optional[Any] = model.get_decoder() decoder.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Any = MaMaaaDecoder.from_pretrained(_a ).to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = decoder( input_ids=inputs_dict["""decoder_input_ids"""] , attention_mask=inputs_dict["""decoder_attention_mask"""] , encoder_hidden_states=_a , encoder_attention_mask=inputs_dict["""attention_mask"""] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :str = (MaMaaaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :Dict = ( { """conversational""": MaMaaaForConditionalGeneration, """feature-extraction""": MaMaaaModel, """summarization""": MaMaaaForConditionalGeneration, """text2text-generation""": MaMaaaForConditionalGeneration, """translation""": MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Optional[int] = True _SCREAMING_SNAKE_CASE :str = False _SCREAMING_SNAKE_CASE :Optional[int] = False def _a ( self , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = MaMaaaModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ConfigTester(self , config_class=_a ) def _a ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(_a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = model_class.from_pretrained(_a , output_loading_info=_a ) self.assertEqual(info["""missing_keys"""] , [] ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_a ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): SCREAMING_SNAKE_CASE__ : int = model_class(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = copy.deepcopy(self._prepare_for_class(_a , _a ) ) if not self.is_encoder_decoder: SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""] del inputs["input_ids"] else: SCREAMING_SNAKE_CASE__ : str = inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Dict = inputs.get("""decoder_input_ids""" , _a ) del inputs["input_ids"] inputs.pop("""decoder_input_ids""" , _a ) SCREAMING_SNAKE_CASE__ : str = model.get_input_embeddings() if not self.is_encoder_decoder: SCREAMING_SNAKE_CASE__ : int = wte(_a ) else: SCREAMING_SNAKE_CASE__ : Dict = wte(_a ) SCREAMING_SNAKE_CASE__ : str = wte(_a ) with torch.no_grad(): model(**_a )[0] def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(1 ).to(_a ) SCREAMING_SNAKE_CASE__ : str = MaMaaaForConditionalGeneration(_a ).eval().to(_a ) if torch_device == "cuda": model.half() model.generate(_a , attention_mask=_a ) model.generate(num_beams=4 , do_sample=_a , early_stopping=_a , num_return_sequences=3 ) def _lowercase ( __lowerCAmelCase ) -> int: return torch.tensor(__lowerCAmelCase , dtype=torch.long , device=__lowerCAmelCase ) a :Dict = 1e-4 @require_torch @require_sentencepiece @require_tokenizers @slow class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> Dict: """simple docstring""" return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]] ) SCREAMING_SNAKE_CASE__ : List[str] = _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]] ) SCREAMING_SNAKE_CASE__ : Tuple = prepare_mam_aaa_inputs_dict(model.config , _a , _a ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = torch.Size((1, 11, 1_024) ) self.assertEqual(output.shape , _a ) # change to expected output here SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]] , device=_a ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=_a ) ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(_a ) # change to intended input SCREAMING_SNAKE_CASE__ : Tuple = _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]] ) SCREAMING_SNAKE_CASE__ : Any = _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]] ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_mam_aaa_inputs_dict(model.config , _a , _a ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**_a )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , _a ) # change to expected output here SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]] , device=_a ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=_a ) ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" , src_lang="""fr""" , tgt_lang="""en""" ) SCREAMING_SNAKE_CASE__ : str = [ """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent""" """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de""" """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""", ] # The below article tests that we don't add any hypotheses outside of the top n_beams SCREAMING_SNAKE_CASE__ : str = tokenizer(_a , padding=_a , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.generate( input_ids=dct["""input_ids"""].to(_a ) , attention_mask=dct["""attention_mask"""].to(_a ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id("""en""" ) , ) SCREAMING_SNAKE_CASE__ : Tuple = [ """The NSA case highlights the total absence of intelligence debate""", """I think there are two levels of response from the French government.""", """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.""" """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all""" """ communications in France.""", ] SCREAMING_SNAKE_CASE__ : str = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=_a , skip_special_tokens=_a ) assert generated == expected_en
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = TextToVideoSDPipeline _SCREAMING_SNAKE_CASE :Union[str, Any] = TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE :Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. _SCREAMING_SNAKE_CASE :Any = frozenset( [ """num_inference_steps""", """generator""", """latents""", """return_dict""", """callback""", """callback_steps""", ]) def _a ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_a , set_alpha_to_one=_a , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def _a ( self , _a , _a=0 ) -> int: """simple docstring""" if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Tuple = TextToVideoSDPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : str = """np""" SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).frames SCREAMING_SNAKE_CASE__ : List[Any] = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_a , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def _a ( self ) -> Dict: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_a , expected_max_diff=1E-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def _a ( self ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def _a ( self ) -> Optional[int]: """simple docstring""" pass def _a ( self ) -> str: """simple docstring""" return super().test_progress_bar() @slow @skip_mps class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) SCREAMING_SNAKE_CASE__ : int = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE__ : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE__ : Dict = """Spiderman is surfing""" SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = pipe(_a , generator=_a , num_inference_steps=25 , output_type="""pt""" ).frames SCREAMING_SNAKE_CASE__ : Union[str, Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) SCREAMING_SNAKE_CASE__ : str = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to("""cuda""" ) SCREAMING_SNAKE_CASE__ : Tuple = """Spiderman is surfing""" SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(_a , generator=_a , num_inference_steps=2 , output_type="""pt""" ).frames SCREAMING_SNAKE_CASE__ : Optional[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : Dict = [0] * len_array if len_array > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = array[0] for i in range(1 , _a ): SCREAMING_SNAKE_CASE__ : Tuple = self.prefix_sum[i - 1] + array[i] def _a ( self , _a , _a ) -> int: """simple docstring""" if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _a ( self , _a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_a ) return False if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint 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." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _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 , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging a :Any = logging.get_logger(__name__) a :Optional[Any] = "▁" a :List[str] = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } a :Optional[Any] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } a :Optional[int] = { "facebook/m2m100_418M": 1_024, } # fmt: off a :Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :List[Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Optional[int] = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a , _a , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<pad>" , _a="<unk>" , _a="m2m100" , _a = None , _a=8 , **_a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__ : List[str] = language_codes SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES[language_codes] SCREAMING_SNAKE_CASE__ : Tuple = {lang_code: f'''__{lang_code}__''' for lang_code in fairseq_language_code} SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(_a ) for lang_code in fairseq_language_code if self.get_lang_token(_a ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_a , tgt_lang=_a , bos_token=_a , eos_token=_a , sep_token=_a , unk_token=_a , pad_token=_a , language_codes=_a , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=_a , **_a , ) SCREAMING_SNAKE_CASE__ : List[str] = vocab_file SCREAMING_SNAKE_CASE__ : List[Any] = load_json(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE__ : str = spm_file SCREAMING_SNAKE_CASE__ : List[Any] = load_spm(_a , self.sp_model_kwargs ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(self.encoder ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { self.get_lang_token(_a ): self.encoder_size + i for i, lang_code in enumerate(_a ) } SCREAMING_SNAKE_CASE__ : List[str] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(_a )} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in self.lang_token_to_id.items()} SCREAMING_SNAKE_CASE__ : List[Any] = src_lang if src_lang is not None else """en""" SCREAMING_SNAKE_CASE__ : int = tgt_lang SCREAMING_SNAKE_CASE__ : List[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) SCREAMING_SNAKE_CASE__ : Tuple = num_madeup_words @property def _a ( self ) -> int: """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _a ( self , _a ) -> List[str]: """simple docstring""" return self.sp_model.encode(_a , out_type=_a ) def _a ( self , _a ) -> Dict: """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(_a , self.encoder[self.unk_token] ) def _a ( self , _a ) -> str: """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(_a , self.unk_token ) def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = """""" 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 SCREAMING_SNAKE_CASE__ : Optional[Any] = [] else: current_sub_tokens.append(_a ) out_string += self.sp_model.decode(_a ) return out_string.strip() def _a ( self , _a , _a = None , _a = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) SCREAMING_SNAKE_CASE__ : Tuple = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_a )) + suffix_ones return prefix_ones + ([0] * len(_a )) + ([0] * len(_a )) + suffix_ones def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = {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 ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : Optional[int] = None return state def __setstate__( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Path(_a ) if not save_dir.is_dir(): raise OSError(f'''{save_directory} should be a directory''' ) SCREAMING_SNAKE_CASE__ : Tuple = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : List[str] = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , _a ) if os.path.abspath(self.spm_file ) != os.path.abspath(_a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , _a ) elif not os.path.isfile(self.spm_file ): with open(_a , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ : int = self.sp_model.serialized_model_proto() fi.write(_a ) return (str(_a ), str(_a )) def _a ( self , _a , _a = "en" , _a = None , _a = "ro" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = src_lang SCREAMING_SNAKE_CASE__ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self , _a , _a , _a , **_a ) -> Union[str, Any]: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = src_lang SCREAMING_SNAKE_CASE__ : int = self(_a , add_special_tokens=_a , **_a ) SCREAMING_SNAKE_CASE__ : str = self.get_lang_id(_a ) SCREAMING_SNAKE_CASE__ : Any = tgt_lang_id return inputs def _a ( self ) -> Dict: """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> List[Any]: """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_lang_token(_a ) SCREAMING_SNAKE_CASE__ : str = self.lang_token_to_id[lang_token] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.eos_token_id] def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.get_lang_token(_a ) SCREAMING_SNAKE_CASE__ : Any = self.lang_token_to_id[lang_token] SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.eos_token_id] def _a ( self , _a ) -> str: """simple docstring""" return self.lang_code_to_token[lang] def _a ( self , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_lang_token(_a ) return self.lang_token_to_id[lang_token] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> sentencepiece.SentencePieceProcessor: SCREAMING_SNAKE_CASE__ : Dict = sentencepiece.SentencePieceProcessor(**__lowerCAmelCase ) spm.Load(str(__lowerCAmelCase ) ) return spm def _lowercase ( __lowerCAmelCase ) -> Union[Dict, List]: with open(__lowerCAmelCase , """r""" ) as f: return json.load(__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: with open(__lowerCAmelCase , """w""" ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase , indent=2 )
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 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 if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" from collections import Counter from timeit import timeit def _lowercase ( __lowerCAmelCase = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def _lowercase ( __lowerCAmelCase = "" ) -> bool: if len(__lowerCAmelCase ) == 0: return True SCREAMING_SNAKE_CASE__ : Tuple = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string SCREAMING_SNAKE_CASE__ : dict[str, int] = {} for character in lower_case_input_str: SCREAMING_SNAKE_CASE__ : Any = character_freq_dict.get(__lowerCAmelCase , 0 ) + 1 SCREAMING_SNAKE_CASE__ : Tuple = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def _lowercase ( __lowerCAmelCase = "" ) -> None: print("""\nFor string = """ , __lowerCAmelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(__lowerCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(__lowerCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": a :List[str] = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) a :Optional[int] = can_string_be_rearranged_as_palindrome_counter(check_str) print(f'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from __future__ import annotations a :Dict = 1.6021e-19 # units = C def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""" ) elif mobility < 0: raise ValueError("""mobility cannot be negative""" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) a :Tuple = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys a :Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" import comet # From: unbabel-comet import torch import datasets a :Union[str, Any] = datasets.logging.get_logger(__name__) a :int = "\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel's Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = \"{COMET}: A Neural Framework for {MT} Evaluation\",\n author = \"Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon\",\n booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\",\n month = nov,\n year = \"2020\",\n address = \"Online\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\",\n pages = \"2685--2702\",\n}\n" a :Dict = "\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n" a :Optional[Any] = "\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric('comet')\n >>> # comet_metric = load_metric('comet', 'wmt20-comet-da') # you can also choose which model to use\n >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"]\n >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"]\n >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results[\"scores\"]])\n [0.19, 0.92]\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __a (datasets.Metric): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://unbabel.github.io/COMET/html/index.html""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """sources""": datasets.Value("""string""" , id="""sequence""" ), """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/Unbabel/COMET"""] , reference_urls=[ """https://github.com/Unbabel/COMET""", """https://www.aclweb.org/anthology/2020.emnlp-main.213/""", """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""", ] , ) def _a ( self , _a ) -> Optional[int]: """simple docstring""" if self.config_name == "default": SCREAMING_SNAKE_CASE__ : Optional[int] = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) ) else: SCREAMING_SNAKE_CASE__ : Dict = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def _a ( self , _a , _a , _a , _a=None , _a=False ) -> int: """simple docstring""" if gpus is None: SCREAMING_SNAKE_CASE__ : Dict = 1 if torch.cuda.is_available() else 0 SCREAMING_SNAKE_CASE__ : List[Any] = {"""src""": sources, """mt""": predictions, """ref""": references} SCREAMING_SNAKE_CASE__ : str = [dict(zip(_a , _a ) ) for t in zip(*data.values() )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = self.scorer.predict(_a , gpus=_a , progress_bar=_a ) return {"mean_score": mean_score, "scores": scores}
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device a :Optional[Any] = False class __a (unittest.TestCase): '''simple docstring''' pass @nightly @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = VersatileDiffusionTextToImagePipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) # remove text_unet pipe.remove_unused_weights() pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : str = """A painting of a squirrel eating a burger """ SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : List[str] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = VersatileDiffusionTextToImagePipeline.from_pretrained( """shi-labs/versatile-diffusion""" , torch_dtype=torch.floataa ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """A painting of a squirrel eating a burger """ SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
680
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 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": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import math import sys import cva import numpy as np def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray: # For applying gaussian function for each element in matrix. SCREAMING_SNAKE_CASE__ : Tuple = math.sqrt(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray: SCREAMING_SNAKE_CASE__ : List[Any] = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray: # Creates a gaussian kernel of given dimension. SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros((kernel_size, kernel_size) ) for i in range(0 , __lowerCAmelCase ): for j in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(__lowerCAmelCase , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> np.ndarray: SCREAMING_SNAKE_CASE__ : Tuple = np.zeros(img.shape ) SCREAMING_SNAKE_CASE__ : str = get_gauss_kernel(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_slice(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = img_s - img_s[kernel_size // 2, kernel_size // 2] SCREAMING_SNAKE_CASE__ : int = vec_gaussian(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = np.multiply(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.multiply(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = np.sum(__lowerCAmelCase ) / np.sum(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = val return imga def _lowercase ( __lowerCAmelCase ) -> tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" SCREAMING_SNAKE_CASE__ : Optional[Any] = float(args[2] ) if args[2:] else 1.0 SCREAMING_SNAKE_CASE__ : int = float(args[3] ) if args[3:] else 1.0 if args[4:]: SCREAMING_SNAKE_CASE__ : Tuple = int(args[4] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = kernel_size + abs(kernel_size % 2 - 1 ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": a ,a ,a ,a :Dict = parse_args(sys.argv) a :Tuple = cva.imread(filename, 0) cva.imshow("input image", img) a :List[Any] = img / 255 a :int = out.astype("float32") a :Optional[Any] = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) a :Any = out * 255 a :Any = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable a :List[str] = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a :int = { "configuration_swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = [ "SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST", "Swinv2ForImageClassification", "Swinv2ForMaskedImageModeling", "Swinv2Model", "Swinv2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys a :Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import os from datetime import datetime as dt from github import Github a :List[str] = [ "good first issue", "good second issue", "good difficult issue", "enhancement", "new pipeline/model", "new scheduler", "wip", ] def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = Github(os.environ["""GITHUB_TOKEN"""] ) SCREAMING_SNAKE_CASE__ : Optional[int] = g.get_repo("""huggingface/diffusers""" ) SCREAMING_SNAKE_CASE__ : List[str] = repo.get_issues(state="""open""" ) for issue in open_issues: SCREAMING_SNAKE_CASE__ : Optional[int] = sorted(issue.get_comments() , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = comments[0] if len(__lowerCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a :List[Any] = logging.get_logger(__name__) a :List[Any] = { "facebook/data2vec-text-base": "https://huggingface.co/data2vec/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """data2vec-text""" def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-1_2 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , **_a , ) -> Any: """simple docstring""" super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] = position_embedding_type SCREAMING_SNAKE_CASE__ : List[Any] = use_cache SCREAMING_SNAKE_CASE__ : Tuple = classifier_dropout class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : Any = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a ) -> int: """simple docstring""" super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a = 1 , _a = None , _a = 50 , _a = "pil" , _a = True , **_a , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_a , ) SCREAMING_SNAKE_CASE__ : int = image.to(self.device ) # set step values self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.unet(_a , _a ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler.step(_a , _a , _a ).prev_sample SCREAMING_SNAKE_CASE__ : str = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : str = self.numpy_to_pil(_a ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=_a ), "This is a local test"
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a :List[Any] = get_logger(__name__) class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = """all_checks""" _SCREAMING_SNAKE_CASE :List[str] = """basic_checks""" _SCREAMING_SNAKE_CASE :Optional[int] = """no_checks""" class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None ) -> str: if expected_checksums is None: logger.info("""Unable to verify checksums.""" ) return if len(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) ) if len(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) > 0: raise UnexpectedDownloadedFile(str(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE__ : str = """ for """ + verification_name if verification_name is not None else """""" if len(__lowerCAmelCase ) > 0: raise NonMatchingChecksumError( F'''Checksums didn\'t match{for_verification_name}:\n''' F'''{bad_urls}\n''' """Set `verification_mode='no_checks'` to skip checksums verification and ignore this error""" ) logger.info("""All the checksums matched successfully""" + for_verification_name ) class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' class __a (UpperCamelCase_): '''simple docstring''' def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: if expected_splits is None: logger.info("""Unable to verify splits sizes.""" ) return if len(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) > 0: raise ExpectedMoreSplits(str(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) ) if len(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) > 0: raise UnexpectedSplits(str(set(__lowerCAmelCase ) - set(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = [ {"""expected""": expected_splits[name], """recorded""": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(__lowerCAmelCase ) > 0: raise NonMatchingSplitsSizesError(str(__lowerCAmelCase ) ) logger.info("""All the splits matched successfully.""" ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = True ) -> dict: if record_checksum: SCREAMING_SNAKE_CASE__ : Union[str, Any] = shaaaa() with open(__lowerCAmelCase , """rb""" ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B"""""" ): m.update(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return {"num_bytes": os.path.getsize(__lowerCAmelCase ), "checksum": checksum} def _lowercase ( __lowerCAmelCase ) -> Dict: if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = ["""image_processor""", """tokenizer"""] _SCREAMING_SNAKE_CASE :Any = """Pix2StructImageProcessor""" _SCREAMING_SNAKE_CASE :List[Any] = ("""T5Tokenizer""", """T5TokenizerFast""") def __init__( self , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = False super().__init__(_a , _a ) def __call__( self , _a=None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 2_048 , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = 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 if not self.image_processor.is_vqa: # add pixel_values SCREAMING_SNAKE_CASE__ : Tuple = self.image_processor( _a , return_tensors=_a , max_patches=_a , **_a ) else: # add pixel_values and bbox SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor( _a , return_tensors=_a , max_patches=_a , header_text=_a , **_a ) if text is not None and not self.image_processor.is_vqa: SCREAMING_SNAKE_CASE__ : Optional[int] = 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 , ) if "attention_mask" in text_encoding: SCREAMING_SNAKE_CASE__ : str = text_encoding.pop("""attention_mask""" ) if "input_ids" in text_encoding: SCREAMING_SNAKE_CASE__ : List[Any] = text_encoding.pop("""input_ids""" ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def _a ( self , *_a , **_a ) -> str: """simple docstring""" return self.tokenizer.batch_decode(*_a , **_a ) def _a ( self , *_a , **_a ) -> Optional[int]: """simple docstring""" return self.tokenizer.decode(*_a , **_a ) @property def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : Dict = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
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 a :List[str] = float("nan") class __a : '''simple docstring''' def __init__( self , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = sys.stdout SCREAMING_SNAKE_CASE__ : int = open(_a , """a""" ) def __getattr__( self , _a ) -> List[Any]: """simple docstring""" return getattr(self.stdout , _a ) def _a ( self , _a ) -> Optional[int]: """simple docstring""" self.stdout.write(_a ) # strip tqdm codes self.file.write(re.sub(r"""^.*\r""" , """""" , _a , 0 , re.M ) ) def _lowercase ( __lowerCAmelCase=80 , __lowerCAmelCase=False ) -> Dict: SCREAMING_SNAKE_CASE__ : str = [] # deal with critical env vars SCREAMING_SNAKE_CASE__ : Tuple = ["""CUDA_VISIBLE_DEVICES"""] for key in env_keys: SCREAMING_SNAKE_CASE__ : Tuple = os.environ.get(__lowerCAmelCase , __lowerCAmelCase ) if val is not None: cmd.append(F'''{key}={val}''' ) # python executable (not always needed if the script is executable) SCREAMING_SNAKE_CASE__ : int = sys.executable if full_python_path else sys.executable.split("""/""" )[-1] cmd.append(__lowerCAmelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Dict = """""" while len(__lowerCAmelCase ) > 0: current_line += F'''{cmd.pop(0 )} ''' if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = """""" return "\\\n".join(__lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # unwrap multi-line input SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.sub(r"""[\\\n]+""" , """ """ , args.base_cmd ) # remove --output_dir if any and set our own SCREAMING_SNAKE_CASE__ : int = re.sub("""--output_dir\s+[^\s]+""" , """""" , args.base_cmd ) args.base_cmd += F''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir SCREAMING_SNAKE_CASE__ : str = re.sub("""--overwrite_output_dir\s+""" , """""" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> 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.6_666, 222.22_222_222] )} , ) SCREAMING_SNAKE_CASE__ : List[str] = subprocess.run(__lowerCAmelCase , capture_output=__lowerCAmelCase , text=__lowerCAmelCase ) if verbose: print("""STDOUT""" , result.stdout ) print("""STDERR""" , result.stderr ) # save the streams SCREAMING_SNAKE_CASE__ : Any = variation.replace(""" """ , """-""" ) with open(Path(__lowerCAmelCase ) / F'''log.{prefix}.stdout.txt''' , """w""" ) as f: f.write(result.stdout ) with open(Path(__lowerCAmelCase ) / F'''log.{prefix}.stderr.txt''' , """w""" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("""failed""" ) return {target_metric_key: nan} with io.open(F'''{output_dir}/all_results.json''' , """r""" , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] = json.load(__lowerCAmelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> List[str]: SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = F'''{id}: {variation:<{longest_variation_len}}''' SCREAMING_SNAKE_CASE__ : Any = F'''{preamble}: ''' SCREAMING_SNAKE_CASE__ : Optional[Any] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__lowerCAmelCase ) , desc=__lowerCAmelCase , leave=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = process_run_single( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(__lowerCAmelCase ): metrics.append(__lowerCAmelCase ) results.append(__lowerCAmelCase ) outcome += "✓" else: outcome += "✘" SCREAMING_SNAKE_CASE__ : List[Any] = F'''\33[2K\r{outcome}''' if len(__lowerCAmelCase ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} SCREAMING_SNAKE_CASE__ : Dict = round(mean_metrics[target_metric_key] , 2 ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{outcome} {mean_target}''' if len(__lowerCAmelCase ) > 1: results_str += F''' {tuple(round(__lowerCAmelCase , 2 ) for x in results )}''' print(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = variation return mean_metrics else: print(__lowerCAmelCase ) return {variation_key: variation, target_metric_key: nan} def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.get_device_properties(torch.device("""cuda""" ) ) return F''' Datetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = pd.DataFrame(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = """variation""" SCREAMING_SNAKE_CASE__ : Dict = """diff_%""" SCREAMING_SNAKE_CASE__ : int = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan SCREAMING_SNAKE_CASE__ : Tuple = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__lowerCAmelCase ): # as a fallback, use the minimal value as the sentinel SCREAMING_SNAKE_CASE__ : Union[str, Any] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = df.apply( lambda __lowerCAmelCase : 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 SCREAMING_SNAKE_CASE__ : Optional[Any] = [variation_key, target_metric_key, diff_key, *report_metric_keys] SCREAMING_SNAKE_CASE__ : Any = df.reindex(__lowerCAmelCase , axis="""columns""" ) # reorder cols # capitalize SCREAMING_SNAKE_CASE__ : Optional[int] = df.rename(str.capitalize , axis="""columns""" ) # make the cols as narrow as possible SCREAMING_SNAKE_CASE__ : List[Any] = df.rename(lambda __lowerCAmelCase : c.replace("""_""" , """<br>""" ) , axis="""columns""" ) SCREAMING_SNAKE_CASE__ : int = df.rename(lambda __lowerCAmelCase : c.replace("""_""" , """\n""" ) , axis="""columns""" ) SCREAMING_SNAKE_CASE__ : int = ["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__lowerCAmelCase , floatfmt=""".2f""" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__lowerCAmelCase , floatfmt=""".2f""" )] print("""\n\n""".join(__lowerCAmelCase ) ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() parser.add_argument( """--base-cmd""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Base cmd""" , ) parser.add_argument( """--variations""" , default=__lowerCAmelCase , type=__lowerCAmelCase , nargs="""+""" , required=__lowerCAmelCase , help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'""" , ) parser.add_argument( """--base-variation""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""Baseline variation to compare to. if None the minimal target value will be used to compare against""" , ) parser.add_argument( """--target-metric-key""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second""" , ) parser.add_argument( """--report-metric-keys""" , default="""""" , type=__lowerCAmelCase , help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples""" , ) parser.add_argument( """--repeat-times""" , default=1 , type=__lowerCAmelCase , help="""How many times to re-run each variation - an average will be reported""" , ) parser.add_argument( """--output_dir""" , default="""output_benchmark""" , type=__lowerCAmelCase , help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked""" , ) parser.add_argument( """--verbose""" , default=__lowerCAmelCase , action="""store_true""" , help="""Whether to show the outputs of each run or just the benchmark progress""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Tuple = args.output_dir Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_base_command(__lowerCAmelCase , __lowerCAmelCase ) # split each dimension into its --foo variations SCREAMING_SNAKE_CASE__ : Dict = [list(map(str.strip , re.split(r"""\|""" , __lowerCAmelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(map(str.strip , map(""" """.join , itertools.product(*__lowerCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE__ : str = max(len(__lowerCAmelCase ) for x in variations ) # split wanted keys SCREAMING_SNAKE_CASE__ : Union[str, Any] = args.report_metric_keys.split() # capture prints into a log file for convenience SCREAMING_SNAKE_CASE__ : Dict = 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}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Tee(__lowerCAmelCase ) print(F'''\n*** Running {len(__lowerCAmelCase )} benchmarks:''' ) print(F'''Base command: {' '.join(__lowerCAmelCase )}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """variation""" SCREAMING_SNAKE_CASE__ : Dict = [] for id, variation in enumerate(tqdm(__lowerCAmelCase , desc="""Total completion: """ , leave=__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : Dict = base_cmd + variation.split() results.append( process_run( id + 1 , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.repeat_times , __lowerCAmelCase , args.verbose , ) ) process_results(__lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.base_variation , __lowerCAmelCase ) if __name__ == "__main__": main()
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() a :Tuple = logging.get_logger(__name__) a :Dict = {name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS} def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F'''Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.''' ) if tokenizer_name is None: SCREAMING_SNAKE_CASE__ : Any = TOKENIZER_CLASSES else: SCREAMING_SNAKE_CASE__ : List[Any] = {tokenizer_name: getattr(__lowerCAmelCase , tokenizer_name + """Fast""" )} logger.info(F'''Loading tokenizer classes: {tokenizer_names}''' ) for tokenizer_name in tokenizer_names: SCREAMING_SNAKE_CASE__ : List[Any] = TOKENIZER_CLASSES[tokenizer_name] SCREAMING_SNAKE_CASE__ : Optional[Any] = True if checkpoint_name is None: SCREAMING_SNAKE_CASE__ : Any = list(tokenizer_class.max_model_input_sizes.keys() ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [checkpoint_name] logger.info(F'''For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}''' ) for checkpoint in checkpoint_names: logger.info(F'''Loading {tokenizer_class.__class__.__name__} {checkpoint}''' ) # Load tokenizer SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer_class.from_pretrained(__lowerCAmelCase , force_download=__lowerCAmelCase ) # Save fast tokenizer logger.info(F'''Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}''' ) # For organization names we create sub-directories if "/" in checkpoint: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = checkpoint.split("""/""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) elif add_prefix: SCREAMING_SNAKE_CASE__ : Union[str, Any] = checkpoint SCREAMING_SNAKE_CASE__ : Dict = dump_path else: SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Dict = dump_path logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: SCREAMING_SNAKE_CASE__ : Tuple = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] SCREAMING_SNAKE_CASE__ : Any = file_path.split(__lowerCAmelCase )[-1][0] if next_char == "/": SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = None logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.save_pretrained( __lowerCAmelCase , legacy_format=__lowerCAmelCase , filename_prefix=__lowerCAmelCase ) logger.info(F'''=> File names {file_names}''' ) for file_name in file_names: if not file_name.endswith("""tokenizer.json""" ): os.remove(__lowerCAmelCase ) logger.info(F'''=> removing {file_name}''' ) if __name__ == "__main__": a :str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files." ) parser.add_argument( "--tokenizer_name", default=None, type=str, help=( f'Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ' "download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--checkpoint_name", default=None, type=str, help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.", ) parser.add_argument( "--force_download", action="store_true", help="Re-download checkpoints.", ) a :Optional[int] = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def _lowercase ( __lowerCAmelCase=32 , __lowerCAmelCase=10 , __lowerCAmelCase=100 , __lowerCAmelCase=1026 , __lowerCAmelCase=True , __lowerCAmelCase="data/tokenized_stories_train_wikitext103.jbl" , __lowerCAmelCase="igf_context_pairs.jbl" , ) -> Tuple: set_seed(3 ) # generate train_data and objective_set SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = generate_datasets( __lowerCAmelCase , __lowerCAmelCase , number=__lowerCAmelCase , min_len=1026 , trim=__lowerCAmelCase ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? SCREAMING_SNAKE_CASE__ : Any = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model SCREAMING_SNAKE_CASE__ : int = load_gpta("""gpt2""" ).to(__lowerCAmelCase ) print("""computing perplexity on objective set""" ) SCREAMING_SNAKE_CASE__ : List[Any] = compute_perplexity(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ).item() print("""perplexity on objective set:""" , __lowerCAmelCase ) # collect igf pairs and save to file demo.jbl collect_objective_set(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=15 , __lowerCAmelCase=128 , __lowerCAmelCase=100 , __lowerCAmelCase="igf_model.pt" , ) -> Dict: set_seed(42 ) # Load pre-trained model SCREAMING_SNAKE_CASE__ : Dict = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model SCREAMING_SNAKE_CASE__ : Optional[int] = SecondaryLearner(__lowerCAmelCase ) # Train secondary learner SCREAMING_SNAKE_CASE__ : Optional[Any] = train_secondary_learner( __lowerCAmelCase , __lowerCAmelCase , max_epochs=__lowerCAmelCase , batch_size=__lowerCAmelCase , eval_freq=100 , igf_model_path=__lowerCAmelCase , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=32 , __lowerCAmelCase=1000 , __lowerCAmelCase=16 , __lowerCAmelCase=1.0 , __lowerCAmelCase=recopy_gpta , __lowerCAmelCase=None , __lowerCAmelCase=10 , __lowerCAmelCase="gpt2_finetuned.pt" , ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) SCREAMING_SNAKE_CASE__ : str = RandomSampler(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = DataLoader(__lowerCAmelCase , sampler=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = max_steps // (len(__lowerCAmelCase )) + 1 SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = torch.zeros((1, context_len) , dtype=torch.long , device=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = recopy_model(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) model.train() if secondary_learner is not None: secondary_learner.to(__lowerCAmelCase ) secondary_learner.eval() SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : int = [] # Compute the performance of the transformer model at the beginning SCREAMING_SNAKE_CASE__ : List[str] = compute_perplexity(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) test_perps.append(__lowerCAmelCase ) print("""Test perplexity, step""" , __lowerCAmelCase , """:""" , __lowerCAmelCase ) for epoch in range(int(__lowerCAmelCase ) ): for step, example in enumerate(__lowerCAmelCase ): torch.cuda.empty_cache() SCREAMING_SNAKE_CASE__ : List[Any] = random.randint(0 , example.size(2 ) - context_len - 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(__lowerCAmelCase , labels=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = True if secondary_learner is not None: SCREAMING_SNAKE_CASE__ : str = secondary_learner.forward( torch.tensor(__lowerCAmelCase , dtype=torch.long , device=__lowerCAmelCase ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__lowerCAmelCase ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: SCREAMING_SNAKE_CASE__ : str = -1 if predicted_q < threshold: SCREAMING_SNAKE_CASE__ : Any = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE__ : List[Any] = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: SCREAMING_SNAKE_CASE__ : Any = compute_perplexity(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) test_perps.append(__lowerCAmelCase ) print("""Test perplexity, step""" , __lowerCAmelCase , """:""" , __lowerCAmelCase ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __lowerCAmelCase ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def _lowercase ( ) -> int: SCREAMING_SNAKE_CASE__ : Any = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=__lowerCAmelCase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=__lowerCAmelCase , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=__lowerCAmelCase , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1000 , type=__lowerCAmelCase , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=__lowerCAmelCase , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=__lowerCAmelCase , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=__lowerCAmelCase , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=__lowerCAmelCase , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1026 , type=__lowerCAmelCase , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=__lowerCAmelCase , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=__lowerCAmelCase , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__lowerCAmelCase , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=__lowerCAmelCase , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner SCREAMING_SNAKE_CASE__ : int = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner SCREAMING_SNAKE_CASE__ : Dict = training_secondary_learner( __lowerCAmelCase , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1026 , trim=__lowerCAmelCase ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=__lowerCAmelCase , secondary_learner=__lowerCAmelCase , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs a :Optional[Any] = imread(r"digital_image_processing/image_data/lena_small.jpg") a :Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowercase ( ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = cn.convert_to_negative(__lowerCAmelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowercase ( ) -> Tuple: with Image.open("""digital_image_processing/image_data/lena_small.jpg""" ) as img: # Work around assertion for response assert str(cc.change_contrast(__lowerCAmelCase , 110 ) ).startswith( """<PIL.Image.Image image mode=RGB size=100x100 at""" ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : List[Any] = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Any = imread("""digital_image_processing/image_data/lena_small.jpg""" , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(__lowerCAmelCase ) # assert canny array for at least one True assert canny_array.any() def _lowercase ( ) -> Dict: assert gg.gaussian_filter(__lowerCAmelCase , 5 , sigma=0.9 ).all() def _lowercase ( ) -> str: # laplace diagonals SCREAMING_SNAKE_CASE__ : Dict = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = conv.img_convolve(__lowerCAmelCase , __lowerCAmelCase ).astype(__lowerCAmelCase ) assert res.any() def _lowercase ( ) -> int: assert med.median_filter(__lowerCAmelCase , 3 ).any() def _lowercase ( ) -> List[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = sob.sobel_filter(__lowerCAmelCase ) assert grad.any() and theta.any() def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(__lowerCAmelCase , 20 ) assert sepia.all() def _lowercase ( __lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg" ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = bs.Burkes(imread(__lowerCAmelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowercase ( __lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg" , ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = rs.NearestNeighbour(imread(__lowerCAmelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Tuple = """digital_image_processing/image_data/lena.jpg""" # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Tuple = imread(__lowerCAmelCase , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : int = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : Tuple = lbp.get_neighbors_pixel( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Any = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : List[Any] = lbp.local_binary_value(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) assert lbp_image.any()
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": a :Optional[int] = argparse.ArgumentParser( description=( "Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="roberta", choices=["roberta", "gpt2"]) parser.add_argument("--model_name", default="roberta-large", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_roberta_048131723.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") a :List[str] = parser.parse_args() if args.model_type == "roberta": a :Union[str, Any] = RobertaForMaskedLM.from_pretrained(args.model_name) a :Dict = "roberta" elif args.model_type == "gpt2": a :Tuple = GPTaLMHeadModel.from_pretrained(args.model_name) a :Dict = "transformer" a :int = model.state_dict() a :Any = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: a :int = state_dict[f'{prefix}.{param_name}'] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: a :str = f'{prefix}.embeddings.{w}.weight' a :List[Any] = state_dict[param_name] for w in ["weight", "bias"]: a :str = f'{prefix}.embeddings.LayerNorm.{w}' a :Union[str, Any] = state_dict[param_name] # Transformer Blocks # a :Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: a :Optional[int] = state_dict[ f'{prefix}.h.{teacher_idx}.{layer}.{w}' ] a :str = state_dict[f'{prefix}.h.{teacher_idx}.attn.bias'] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: a :Optional[Any] = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: a :Union[str, Any] = state_dict[f'{layer}'] if args.vocab_transform: for w in ["weight", "bias"]: a :Tuple = state_dict[f'lm_head.dense.{w}'] a :Optional[int] = state_dict[f'lm_head.layer_norm.{w}'] elif args.model_type == "gpt2": for w in ["weight", "bias"]: a :Optional[int] = state_dict[f'{prefix}.ln_f.{w}'] a :Optional[Any] = state_dict["lm_head.weight"] print(f'N layers selected for distillation: {std_idx}') print(f'Number of params transferred for distillation: {len(compressed_sd.keys())}') print(f'Save transferred checkpoint to {args.dump_checkpoint}.') torch.save(compressed_sd, args.dump_checkpoint)
680
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint 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." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
1
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with blanks.csv"""] ) @pytest.mark.parametrize("""revision""" , [None, """v2"""] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[Any] = hf_hub_url(repo_id=__lowerCAmelCase , path=__lowerCAmelCase , revision=__lowerCAmelCase ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(__lowerCAmelCase )}'''
680
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _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 , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
1
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow a :Optional[int] = False class __a (unittest.TestCase): '''simple docstring''' def _a ( self , _a=32 ) -> Tuple: """simple docstring""" set_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = UNetaDModel(sample_size=_a , in_channels=3 , out_channels=3 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable SCREAMING_SNAKE_CASE__ : int = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=_a , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(_a ) for _ in range(4 )] SCREAMING_SNAKE_CASE__ : Dict = [torch.randn((4, 3, 32, 32) ).to(_a ) for _ in range(4 )] SCREAMING_SNAKE_CASE__ : Any = [torch.randint(0 , 1_000 , (4,) ).long().to(_a ) for _ in range(4 )] # train with a DDPM scheduler SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() SCREAMING_SNAKE_CASE__ : List[Any] = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a , timesteps[i] ).sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() SCREAMING_SNAKE_CASE__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , timesteps[i] ).sample SCREAMING_SNAKE_CASE__ : List[str] = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) ) self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) )
680
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 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 if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
1
"""simple docstring""" from PIL import Image def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Image: SCREAMING_SNAKE_CASE__ : int = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__lowerCAmelCase ) -> int: return int(128 + factor * (c - 128) ) return img.point(__lowerCAmelCase ) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change contrast to 170 a :Optional[int] = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :Tuple = logging.get_logger(__name__) a :Union[str, Any] = { "naver-clova-ix/donut-base": "https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json", # See all Donut models at https://huggingface.co/models?filter=donut-swin } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = """donut-swin""" _SCREAMING_SNAKE_CASE :Optional[int] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=[2, 2, 6, 2] , _a=[3, 6, 12, 24] , _a=7 , _a=4.0 , _a=True , _a=0.0 , _a=0.0 , _a=0.1 , _a="gelu" , _a=False , _a=0.02 , _a=1E-5 , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : Tuple = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = embed_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = depths SCREAMING_SNAKE_CASE__ : Optional[int] = len(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_heads SCREAMING_SNAKE_CASE__ : Dict = window_size SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ : Any = int(embed_dim * 2 ** (len(_a ) - 1) )
680
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
1
"""simple docstring""" import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=100 , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=4 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=3 , _a=None , _a=[0, 1, 2, 3] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Dict = 100 SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : Dict = scope SCREAMING_SNAKE_CASE__ : Tuple = out_indices SCREAMING_SNAKE_CASE__ : Tuple = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : List[Any] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Optional[int] = num_patches + 1 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None SCREAMING_SNAKE_CASE__ : int = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any = self.get_config() return config, pixel_values, labels, pixel_labels def _a ( self ) -> List[Any]: """simple docstring""" return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def _a ( self , _a , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitForMaskedImageModeling(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def _a ( self , _a , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = BeitForImageClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : int = 1 SCREAMING_SNAKE_CASE__ : List[str] = BeitForImageClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self , _a , _a , _a , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE__ : int = BeitForSemanticSegmentation(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :List[str] = ( { """feature-extraction""": BeitModel, """image-classification""": BeitForImageClassification, """image-segmentation""": BeitForSemanticSegmentation, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :List[str] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :str = False def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BeitModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _a ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""BEiT does not use inputs_embeds""" ) def _a ( self ) -> str: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def _a ( self ) -> Any: """simple docstring""" pass def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Any = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) def _a ( self ) -> Tuple: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(_a ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(_a ) model.to(_a ) model.train() SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(_a , _a , return_labels=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(**_a ).loss loss.backward() def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : int = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(_a ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE__ : int = model_class(_a ) model.gradient_checkpointing_enable() model.to(_a ) model.train() SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(_a , _a , return_labels=_a ) SCREAMING_SNAKE_CASE__ : int = model(**_a ).loss loss.backward() def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Tuple = _config_zero_init(_a ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Any = model_class(config=_a ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def _a ( self ) -> Optional[Any]: """simple docstring""" for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[str] = BeitModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _lowercase ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> Optional[int]: """simple docstring""" return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224""" ) if is_vision_available() else None @slow def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k""" ).to(_a ) SCREAMING_SNAKE_CASE__ : int = self.default_image_processor SCREAMING_SNAKE_CASE__ : str = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=_a , return_tensors="""pt""" ).pixel_values.to(_a ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE__ : Dict = torch.ones((1, 196) , dtype=torch.bool ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(pixel_values=_a , bool_masked_pos=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 196, 8_192) ) self.assertEqual(logits.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(_a ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , _a , atol=1E-2 ) ) @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224""" ).to(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[str] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**_a ) SCREAMING_SNAKE_CASE__ : str = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Any = torch.Size((1, 1_000) ) self.assertEqual(logits.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(_a ) self.assertTrue(torch.allclose(logits[0, :3] , _a , atol=1E-4 ) ) SCREAMING_SNAKE_CASE__ : int = 281 self.assertEqual(logits.argmax(-1 ).item() , _a ) @slow def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k""" ).to( _a ) SCREAMING_SNAKE_CASE__ : List[str] = self.default_image_processor SCREAMING_SNAKE_CASE__ : int = prepare_img() SCREAMING_SNAKE_CASE__ : int = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size((1, 21_841) ) self.assertEqual(logits.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(_a ) self.assertTrue(torch.allclose(logits[0, :3] , _a , atol=1E-4 ) ) SCREAMING_SNAKE_CASE__ : int = 2_396 self.assertEqual(logits.argmax(-1 ).item() , _a ) @slow def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640""" ) SCREAMING_SNAKE_CASE__ : Tuple = model.to(_a ) SCREAMING_SNAKE_CASE__ : str = BeitImageProcessor(do_resize=_a , size=640 , do_center_crop=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) SCREAMING_SNAKE_CASE__ : str = Image.open(ds[0]["""file"""] ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**_a ) SCREAMING_SNAKE_CASE__ : Any = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape , _a ) SCREAMING_SNAKE_CASE__ : int = version.parse(PIL.__version__ ) < version.parse("""9.0.0""" ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE__ : int = torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] , device=_a , ) else: SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640""" ) SCREAMING_SNAKE_CASE__ : Any = model.to(_a ) SCREAMING_SNAKE_CASE__ : Dict = BeitImageProcessor(do_resize=_a , size=640 , do_center_crop=_a ) SCREAMING_SNAKE_CASE__ : int = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.open(ds[0]["""file"""] ) SCREAMING_SNAKE_CASE__ : Any = image_processor(images=_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ : Dict = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE__ : Any = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , _a ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor.post_process_semantic_segmentation(outputs=_a ) SCREAMING_SNAKE_CASE__ : str = torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape , _a )
680
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
1
"""simple docstring""" import csv import tweepy # Twitter API credentials a :Tuple = "" a :Union[str, Any] = "" a :Optional[int] = "" a :Dict = "" def _lowercase ( __lowerCAmelCase ) -> None: # authorize twitter, initialize tweepy SCREAMING_SNAKE_CASE__ : Union[str, Any] = tweepy.OAuthHandler(__lowerCAmelCase , __lowerCAmelCase ) auth.set_access_token(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = tweepy.API(__lowerCAmelCase ) # initialize a list to hold all the tweepy Tweets SCREAMING_SNAKE_CASE__ : Optional[int] = [] # make initial request for most recent tweets (200 is the maximum allowed count) SCREAMING_SNAKE_CASE__ : Union[str, Any] = api.user_timeline(screen_name=__lowerCAmelCase , count=200 ) # save most recent tweets alltweets.extend(__lowerCAmelCase ) # save the id of the oldest tweet less one SCREAMING_SNAKE_CASE__ : str = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(__lowerCAmelCase ) > 0: print(F'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates SCREAMING_SNAKE_CASE__ : Optional[int] = api.user_timeline( screen_name=__lowerCAmelCase , count=200 , max_id=__lowerCAmelCase ) # save most recent tweets alltweets.extend(__lowerCAmelCase ) # update the id of the oldest tweet less one SCREAMING_SNAKE_CASE__ : str = alltweets[-1].id - 1 print(F'''...{len(__lowerCAmelCase )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv SCREAMING_SNAKE_CASE__ : int = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F'''new_{screen_name}_tweets.csv''' , """w""" ) as f: SCREAMING_SNAKE_CASE__ : Any = csv.writer(__lowerCAmelCase ) writer.writerow(["""id""", """created_at""", """text"""] ) writer.writerows(__lowerCAmelCase ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("FirePing32")
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 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 if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 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": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=10 , _a=3 , _a=2 , _a=2 , _a=2 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=0.9 , _a=None , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : List[str] = batch_size SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : str = num_channels SCREAMING_SNAKE_CASE__ : Dict = patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = tubelet_size SCREAMING_SNAKE_CASE__ : str = num_frames SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : str = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = mask_ratio SCREAMING_SNAKE_CASE__ : List[str] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame SCREAMING_SNAKE_CASE__ : str = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos SCREAMING_SNAKE_CASE__ : str = int(mask_ratio * self.seq_length ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = self.get_config() return config, pixel_values, labels def _a ( self ) -> Dict: """simple docstring""" return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=_a , initializer_range=self.initializer_range , ) def _a ( self , _a , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = VideoMAEModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = VideoMAEForPreTraining(_a ) model.to(_a ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones((self.num_masks,) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) SCREAMING_SNAKE_CASE__ : List[str] = mask.expand(self.batch_size , -1 ).bool() SCREAMING_SNAKE_CASE__ : str = model(_a , _a ) # model only returns predictions for masked patches SCREAMING_SNAKE_CASE__ : List[str] = mask.sum().item() SCREAMING_SNAKE_CASE__ : Dict = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Dict = ( {"""feature-extraction""": VideoMAEModel, """video-classification""": VideoMAEForVideoClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :int = False _SCREAMING_SNAKE_CASE :int = False _SCREAMING_SNAKE_CASE :Any = False _SCREAMING_SNAKE_CASE :int = False def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = VideoMAEModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def _a ( self , _a , _a , _a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = copy.deepcopy(_a ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch SCREAMING_SNAKE_CASE__ : int = torch.ones((self.model_tester.num_masks,) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) SCREAMING_SNAKE_CASE__ : Tuple = mask.expand(self.model_tester.batch_size , -1 ).bool() SCREAMING_SNAKE_CASE__ : Optional[Any] = bool_masked_pos.to(_a ) if return_labels: if model_class in [ *get_values(_a ), ]: SCREAMING_SNAKE_CASE__ : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""VideoMAE does not use inputs_embeds""" ) def _a ( self ) -> List[Any]: """simple docstring""" pass def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : int = model_class(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = VideoMAEModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _a ( self ) -> Tuple: """simple docstring""" if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.seq_length - self.model_tester.num_masks SCREAMING_SNAKE_CASE__ : List[str] = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Any = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : int = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : List[str] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 1 , len(_a ) ) SCREAMING_SNAKE_CASE__ : int = outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _a ( self ) -> List[Any]: """simple docstring""" def check_hidden_states_output(_a , _a , _a ): SCREAMING_SNAKE_CASE__ : List[Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**self._prepare_for_class(_a , _a ) ) SCREAMING_SNAKE_CASE__ : int = outputs.hidden_states SCREAMING_SNAKE_CASE__ : Any = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(_a ) , _a ) SCREAMING_SNAKE_CASE__ : int = self.model_tester.seq_length - self.model_tester.num_masks SCREAMING_SNAKE_CASE__ : Optional[Any] = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : List[str] = True check_hidden_states_output(_a , _a , _a ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _a ( self ) -> Tuple: """simple docstring""" pass def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : List[Any] = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" ) SCREAMING_SNAKE_CASE__ : Tuple = np.load(__lowerCAmelCase ) return list(__lowerCAmelCase ) @require_torch @require_vision class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> List[str]: """simple docstring""" return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics""" ).to( _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : int = prepare_video() SCREAMING_SNAKE_CASE__ : str = image_processor(_a , return_tensors="""pt""" ).to(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**_a ) # verify the logits SCREAMING_SNAKE_CASE__ : str = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , _a ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor([0.3_669, -0.0_688, -0.2_421] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""" ).to(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = prepare_video() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""pt""" ).to(_a ) # add boolean mask, indicating which patches to mask SCREAMING_SNAKE_CASE__ : Union[str, Any] = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" , filename="""bool_masked_pos.pt""" ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(_a ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**_a ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size([1, 1_408, 1_536] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor( [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] , device=_a ) self.assertEqual(outputs.logits.shape , _a ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _a , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([0.5_142] , device=_a ) self.assertTrue(torch.allclose(outputs.loss , _a , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) SCREAMING_SNAKE_CASE__ : int = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""" , norm_pix_loss=_a ).to( _a ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**_a ) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor(torch.tensor([0.6_469] ) , device=_a ) self.assertTrue(torch.allclose(outputs.loss , _a , atol=1E-4 ) )
680
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
1
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file SCREAMING_SNAKE_CASE__ : Optional[int] = TapasConfig.from_json_file(__lowerCAmelCase ) # set absolute/relative position embeddings parameter SCREAMING_SNAKE_CASE__ : List[str] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": SCREAMING_SNAKE_CASE__ : Optional[Any] = TapasForQuestionAnswering(config=__lowerCAmelCase ) elif task == "WTQ": # run_task_main.py hparams SCREAMING_SNAKE_CASE__ : Any = 4 SCREAMING_SNAKE_CASE__ : Dict = True # hparam_utils.py hparams SCREAMING_SNAKE_CASE__ : Any = 0.664_694 SCREAMING_SNAKE_CASE__ : List[Any] = 0.207_951 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0.121_194 SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = 0.0_352_513 SCREAMING_SNAKE_CASE__ : List[str] = TapasForQuestionAnswering(config=__lowerCAmelCase ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams SCREAMING_SNAKE_CASE__ : Optional[Any] = 4 SCREAMING_SNAKE_CASE__ : Dict = False # hparam_utils.py hparams SCREAMING_SNAKE_CASE__ : Optional[int] = 36.4_519 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.903_421 SCREAMING_SNAKE_CASE__ : List[Any] = 222.088 SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : Any = 0.763_141 SCREAMING_SNAKE_CASE__ : Tuple = TapasForQuestionAnswering(config=__lowerCAmelCase ) elif task == "TABFACT": SCREAMING_SNAKE_CASE__ : List[str] = TapasForSequenceClassification(config=__lowerCAmelCase ) elif task == "MLM": SCREAMING_SNAKE_CASE__ : Tuple = TapasForMaskedLM(config=__lowerCAmelCase ) elif task == "INTERMEDIATE_PRETRAINING": SCREAMING_SNAKE_CASE__ : Optional[Any] = TapasModel(config=__lowerCAmelCase ) else: raise ValueError(F'''Task {task} not supported.''' ) print(F'''Building PyTorch model from configuration: {config}''' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Save pytorch-model (weights and configuration) print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__lowerCAmelCase ) # Save tokenizer files print(F'''Save tokenizer files to {pytorch_dump_path}''' ) SCREAMING_SNAKE_CASE__ : Dict = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=512 ) tokenizer.save_pretrained(__lowerCAmelCase ) print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--task", default="SQA", type=str, help="Model task for which to convert a checkpoint. Defaults to SQA." ) parser.add_argument( "--reset_position_index_per_cell", default=False, action="store_true", help="Whether to use relative position embeddings or not. Defaults to True.", ) parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--tapas_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained TAPAS 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." ) a :Dict = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration a :List[str] = pytest.mark.integration a :List[str] = {"comet"} a :Any = importlib.util.find_spec("fairseq") is not None a :str = {"code_eval"} a :List[Any] = os.name == "nt" a :Tuple = {"bertscore", "frugalscore", "perplexity"} a :str = importlib.util.find_spec("transformers") is not None def _lowercase ( __lowerCAmelCase ) -> Optional[int]: @wraps(__lowerCAmelCase ) def wrapper(self , __lowerCAmelCase ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("""\"test requires Fairseq\"""" ) else: test_case(self , __lowerCAmelCase ) return wrapper def _lowercase ( __lowerCAmelCase ) -> Optional[Any]: @wraps(__lowerCAmelCase ) def wrapper(self , __lowerCAmelCase ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("""\"test requires transformers\"""" ) else: test_case(self , __lowerCAmelCase ) return wrapper def _lowercase ( __lowerCAmelCase ) -> List[Any]: @wraps(__lowerCAmelCase ) def wrapper(self , __lowerCAmelCase ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("""\"test not supported on Windows\"""" ) else: test_case(self , __lowerCAmelCase ) return wrapper def _lowercase ( ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("""./metrics/*/""" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names()) @for_all_test_methods( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) @local class __a (parameterized.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = {} _SCREAMING_SNAKE_CASE :str = None @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""" ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = """[...]""" SCREAMING_SNAKE_CASE__ : Optional[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , _a ) ).module_path ) SCREAMING_SNAKE_CASE__ : int = datasets.load.import_main_class(metric_module.__name__ , dataset=_a ) # check parameters SCREAMING_SNAKE_CASE__ : str = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(_a , metric_module.__name__ ): with self.use_local_metrics(): try: SCREAMING_SNAKE_CASE__ : Union[str, Any] = doctest.testmod(_a , verbose=_a , raise_on_error=_a ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = """[...]""" SCREAMING_SNAKE_CASE__ : List[str] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , _a ) ).module_path ) # run doctest with self.use_local_metrics(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = doctest.testmod(_a , verbose=_a , raise_on_error=_a ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def _a ( self , _a , _a ) -> Union[str, Any]: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](_a ): yield else: yield @contextmanager def _a ( self ) -> str: """simple docstring""" def load_local_metric(_a , *_a , **_a ): return load_metric(os.path.join("""metrics""" , _a ) , *_a , **_a ) with patch("""datasets.load_metric""" ) as mock_load_metric: SCREAMING_SNAKE_CASE__ : Dict = load_local_metric yield @classmethod def _a ( cls , _a ) -> Optional[Any]: """simple docstring""" def wrapper(_a ): SCREAMING_SNAKE_CASE__ : Optional[int] = contextmanager(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("""bleurt""" ) def _lowercase ( __lowerCAmelCase ) -> List[Any]: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("""sv""" , """""" , """""" ) # handle pytest cli flags class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a ) -> Tuple: """simple docstring""" assert len(input_dict["""input_ids"""] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("""bleurt.score._create_predictor""" ) as mock_create_predictor: SCREAMING_SNAKE_CASE__ : str = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("""bertscore""" ) def _lowercase ( __lowerCAmelCase ) -> List[str]: import torch def bert_cos_score_idf(__lowerCAmelCase , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ): return torch.tensor([[1.0, 1.0, 1.0]] * len(__lowerCAmelCase ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("""bert_score.scorer.get_model""" ), patch( """bert_score.scorer.bert_cos_score_idf""" ) as mock_bert_cos_score_idf: SCREAMING_SNAKE_CASE__ : str = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("""comet""" ) def _lowercase ( __lowerCAmelCase ) -> Dict: def load_from_checkpoint(__lowerCAmelCase ): class __a : '''simple docstring''' def _a ( self , _a , *_a , **_a ) -> Tuple: """simple docstring""" assert len(_a ) == 2 SCREAMING_SNAKE_CASE__ : str = [0.19, 0.92] return scores, sum(_a ) / len(_a ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("""comet.download_model""" ) as mock_download_model: SCREAMING_SNAKE_CASE__ : Any = None with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint: SCREAMING_SNAKE_CASE__ : str = load_from_checkpoint yield def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Tuple = load_metric(os.path.join("""metrics""" , """seqeval""" ) ) SCREAMING_SNAKE_CASE__ : List[str] = """ERROR""" SCREAMING_SNAKE_CASE__ : Optional[int] = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(__lowerCAmelCase , match=re.escape(__lowerCAmelCase ) ): metric.compute(predictions=[] , references=[] , scheme=__lowerCAmelCase )
680
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
1
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator() accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" ) test_default_ensures_even_batch_sizes() accelerator.print("""Run tests with even_batches disabled""" ) test_can_disable_even_batches() accelerator.print("""Test joining uneven inputs""" ) test_can_join_uneven_inputs() accelerator.print("""Test overriding even_batches when joining uneven inputs""" ) test_join_can_override_even_batches() accelerator.print("""Test overriding even_batches for mixed dataloader types""" ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("""Test join with non DDP distributed raises warning""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
1
"""simple docstring""" import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: # Initialise PyTorch model SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaConfig.from_json_file(__lowerCAmelCase ) print(F'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ : Dict = TaForConditionalGeneration(__lowerCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_ta(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": a :str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_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 T5 model. \nThis specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
680
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
1
"""simple docstring""" from string import ascii_uppercase a :str = {char: i for i, char in enumerate(ascii_uppercase)} a :str = dict(enumerate(ascii_uppercase)) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : str = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = 0 while True: if x == i: SCREAMING_SNAKE_CASE__ : List[str] = 0 if len(__lowerCAmelCase ) == len(__lowerCAmelCase ): break key += key[i] i += 1 return key def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = """""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 for letter in message: if letter == " ": cipher_text += " " else: SCREAMING_SNAKE_CASE__ : Optional[int] = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = """""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: SCREAMING_SNAKE_CASE__ : List[str] = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ : List[Any] = """THE GERMAN ATTACK""" SCREAMING_SNAKE_CASE__ : Tuple = """SECRET""" SCREAMING_SNAKE_CASE__ : str = generate_key(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = cipher_text(__lowerCAmelCase , __lowerCAmelCase ) print(F'''Encrypted Text = {s}''' ) print(F'''Original Text = {original_text(__lowerCAmelCase , __lowerCAmelCase )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
680
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
1
"""simple docstring""" import argparse import copy def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = {} with open(__lowerCAmelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE__ : int = [] _list.append([line.split()[1], line.split()[2]] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: SCREAMING_SNAKE_CASE__ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: with open(__lowerCAmelCase ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] = f.read(1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = start_node SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[str] = start_node SCREAMING_SNAKE_CASE__ : List[str] = 0 while visiting not in first_solution: SCREAMING_SNAKE_CASE__ : Tuple = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__lowerCAmelCase ) and k[0] not in first_solution: SCREAMING_SNAKE_CASE__ : Any = k[1] SCREAMING_SNAKE_CASE__ : int = k[0] first_solution.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = distance_of_first_solution + int(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = best_node first_solution.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[str] = [] for n in solution[1:-1]: SCREAMING_SNAKE_CASE__ : str = solution.index(__lowerCAmelCase ) for kn in solution[1:-1]: SCREAMING_SNAKE_CASE__ : int = solution.index(__lowerCAmelCase ) if n == kn: continue SCREAMING_SNAKE_CASE__ : Optional[Any] = copy.deepcopy(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = kn SCREAMING_SNAKE_CASE__ : List[Any] = n SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for k in _tmp[:-1]: SCREAMING_SNAKE_CASE__ : Any = _tmp[_tmp.index(__lowerCAmelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: SCREAMING_SNAKE_CASE__ : Tuple = distance + int(i[1] ) _tmp.append(__lowerCAmelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) SCREAMING_SNAKE_CASE__ : Tuple = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __lowerCAmelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = first_solution SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = distance_of_first_solution SCREAMING_SNAKE_CASE__ : str = solution while count <= iters: SCREAMING_SNAKE_CASE__ : Any = find_neighborhood(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : List[Any] = neighborhood[index_of_best_solution] SCREAMING_SNAKE_CASE__ : Tuple = len(__lowerCAmelCase ) - 1 SCREAMING_SNAKE_CASE__ : Any = False while not found: SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 while i < len(__lowerCAmelCase ): if best_solution[i] != solution[i]: SCREAMING_SNAKE_CASE__ : Any = best_solution[i] SCREAMING_SNAKE_CASE__ : Tuple = solution[i] break SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = best_solution[:-1] SCREAMING_SNAKE_CASE__ : List[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: SCREAMING_SNAKE_CASE__ : List[Any] = cost SCREAMING_SNAKE_CASE__ : Optional[int] = solution else: SCREAMING_SNAKE_CASE__ : List[Any] = index_of_best_solution + 1 SCREAMING_SNAKE_CASE__ : List[Any] = neighborhood[index_of_best_solution] if len(__lowerCAmelCase ) >= size: tabu_list.pop(0 ) SCREAMING_SNAKE_CASE__ : int = count + 1 return best_solution_ever, best_cost def _lowercase ( __lowerCAmelCase=None ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = generate_neighbours(args.File ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = generate_first_solution( args.File , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = tabu_search( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": a :Dict = 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())
680
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase): '''simple docstring''' @property def _a ( self ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_uncond_unet SCREAMING_SNAKE_CASE__ : List[Any] = PNDMScheduler() SCREAMING_SNAKE_CASE__ : Union[str, Any] = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pndm(generator=_a , num_inference_steps=20 , output_type="""numpy""" ).images SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = pndm(generator=_a , num_inference_steps=20 , output_type="""numpy""" , return_dict=_a )[0] SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = """google/ddpm-cifar10-32""" SCREAMING_SNAKE_CASE__ : str = UNetaDModel.from_pretrained(_a ) SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler() SCREAMING_SNAKE_CASE__ : Any = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = pndm(generator=_a , output_type="""numpy""" ).images SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
680
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
1
"""simple docstring""" import os import sys import unittest a :str = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) a :Dict = os.path.join("tests", "models", "bert", "test_modeling_bert.py") a :Optional[Any] = os.path.join("tests", "models", "blip", "test_modeling_blip.py") class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = get_test_to_tester_mapping(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_test_to_tester_mapping(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""BertModelTest""": """BertModelTester"""} SCREAMING_SNAKE_CASE__ : Tuple = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_model_to_test_mapping(_a ) SCREAMING_SNAKE_CASE__ : List[str] = get_model_to_test_mapping(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } SCREAMING_SNAKE_CASE__ : int = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_model_to_tester_mapping(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = get_model_to_tester_mapping(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a )
680
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[int] = obj_list.rstrip("""\n""" ).split(""" """ ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule a :List[str] = {"tokenization_tapex": ["TapexTokenizer"]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure)
680
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
1
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=False , _a=False , _a=False , _a=2 , _a=99 , _a=0 , _a=32 , _a=5 , _a=4 , _a=0.1 , _a=0.1 , _a=512 , _a=12 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a="last" , _a=None , _a=None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : List[str] = batch_size SCREAMING_SNAKE_CASE__ : List[str] = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : Dict = use_input_lengths SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : Optional[int] = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = gelu_activation SCREAMING_SNAKE_CASE__ : int = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ : Tuple = causal SCREAMING_SNAKE_CASE__ : Optional[Any] = asm SCREAMING_SNAKE_CASE__ : Tuple = n_langs SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = n_special SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = num_labels SCREAMING_SNAKE_CASE__ : Any = num_choices SCREAMING_SNAKE_CASE__ : List[Any] = summary_type SCREAMING_SNAKE_CASE__ : Dict = use_proj SCREAMING_SNAKE_CASE__ : List[Any] = scope def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ : Tuple = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Dict = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _a ( self ) -> List[Any]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaubertModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(_a , lengths=_a , langs=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , langs=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = FlaubertWithLMHeadModel(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertForQuestionAnsweringSimple(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = model(_a , start_positions=_a , end_positions=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FlaubertForQuestionAnswering(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a ) SCREAMING_SNAKE_CASE__ : str = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , p_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , ) ((SCREAMING_SNAKE_CASE__) , ) : Tuple = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ : List[str] = model(_a , start_positions=_a , end_positions=_a ) ((SCREAMING_SNAKE_CASE__) , ) : Optional[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertForSequenceClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(_a ) SCREAMING_SNAKE_CASE__ : str = 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 _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.num_labels SCREAMING_SNAKE_CASE__ : Any = FlaubertForTokenClassification(_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_choices SCREAMING_SNAKE_CASE__ : int = FlaubertForMultipleChoice(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : int = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _a ( self , _a , _a , _a , _a , _a ) -> List[Any]: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _a ( self , _a , _a , _a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = super()._prepare_for_class(_a , _a , return_labels=_a ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , emb_dim=37 ) def _a ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*_a ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*_a ) @slow def _a ( self ) -> Dict: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @slow @require_torch_gpu def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Any = model_class(config=_a ) SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(_a , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.jit.trace( _a , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_a , os.path.join(_a , """traced_model.pt""" ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.jit.load(os.path.join(_a , """traced_model.pt""" ) , map_location=_a ) loaded(inputs_dict["""input_ids"""].to(_a ) , inputs_dict["""attention_mask"""].to(_a ) ) @require_torch class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(_a )[0] SCREAMING_SNAKE_CASE__ : str = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
680
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a :Optional[int] = logging.get_logger(__name__) a :str = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """xlm-roberta-xl""" def __init__( self , _a=250_880 , _a=2_560 , _a=36 , _a=32 , _a=10_240 , _a="gelu" , _a=0.1 , _a=0.1 , _a=514 , _a=1 , _a=0.02 , _a=1E-0_5 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , **_a , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] = position_embedding_type SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : int = classifier_dropout class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : int = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
680
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
1