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
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A : Any = { """configuration_poolformer""": [ """POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PoolFormerConfig""", """PoolFormerOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any = ["""PoolFormerFeatureExtractor"""] _A : Dict = ["""PoolFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[int] = [ """POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PoolFormerForImageClassification""", """PoolFormerModel""", """PoolFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys _A : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
100
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : _UpperCAmelCase : int = XGLMConfig _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Tuple = '''gelu''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 ,SCREAMING_SNAKE_CASE__ : Tuple=7 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=9_9 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : Tuple=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,): __lowerCamelCase : List[str] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_input_mask __lowerCamelCase : str = use_labels __lowerCamelCase : Any = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : List[str] = ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : Tuple = activation_dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Any = None __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 2 __lowerCamelCase : Dict = 1 def lowerCAmelCase ( self : Any): return XGLMConfig.from_pretrained('facebook/xglm-564M') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) ,clip_value_min=0 ,clip_value_max=3) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : int = self.get_config() __lowerCamelCase : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[Any]): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=SCREAMING_SNAKE_CASE__ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : int): __lowerCamelCase : int = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : str = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : str = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _UpperCAmelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else () _UpperCAmelCase : str = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Tuple = TFXGLMModelTester(self) __lowerCamelCase : int = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,n_embd=3_7) def lowerCAmelCase ( self : List[Any]): self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : str): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.') def lowerCAmelCase ( self : Union[str, Any]): super().test_resize_token_embeddings() @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True): __lowerCamelCase : Any = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]] ,dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __lowerCamelCase : Optional[Any] = [2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1] # fmt: on __lowerCamelCase : int = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') tf.random.set_seed(0) __lowerCamelCase : Optional[Any] = tokenizer('Today is a nice day and' ,return_tensors='tf') __lowerCamelCase : List[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0'): __lowerCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,seed=[7, 0]) __lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = 'left' # use different length sentences to test batching __lowerCamelCase : List[str] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __lowerCamelCase : List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='tf' ,padding=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['input_ids'] __lowerCamelCase : Dict = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=inputs['attention_mask'] ,max_new_tokens=1_2) __lowerCamelCase : Tuple = tokenizer(sentences[0] ,return_tensors='tf').input_ids __lowerCamelCase : List[str] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : Any = tokenizer(sentences[1] ,return_tensors='tf').input_ids __lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tokenizer.decode(output_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[non_padded_sentence, padded_sentence])
652
0
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ : Optional[int] =logging.get_logger(__name__) lowerCAmelCase__ : List[Any] =[ ('bert.bert', 'visual_bert'), ('bert.cls', 'cls'), ('bert.classifier', 'cls'), ('token_type_embeddings_visual', 'visual_token_type_embeddings'), ('position_embeddings_visual', 'visual_position_embeddings'), ('projection', 'visual_projection'), ] lowerCAmelCase__ : Optional[int] =[ 'nlvr2_coco_pre_trained.th', 'nlvr2_fine_tuned.th', 'nlvr2_pre_trained.th', 'vcr_coco_pre_train.th', 'vcr_fine_tune.th', 'vcr_pre_train.th', 'vqa_coco_pre_trained.th', 'vqa_fine_tuned.th', 'vqa_pre_trained.th', ] def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : int = torch.load(A__, map_location='cpu' ) return sd def a__ ( A__, A__, A__=rename_keys_prefix ): SCREAMING_SNAKE_CASE_ : List[Any] = OrderedDict() SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE_ : Any = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE_ : Any = new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE_ : str = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def a__ ( A__, A__ ): assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE_ : List[str] = 'pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE_ : Any = {'visual_embedding_dim': 5_1_2} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE_ : str = {'visual_embedding_dim': 2_0_4_8} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE_ : List[Any] = {'visual_embedding_dim': 2_0_4_8} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE_ : Any = {'visual_embedding_dim': 1_0_2_4} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'visual_embedding_dim': 5_1_2} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE_ : Tuple = {'visual_embedding_dim': 2_0_4_8} SCREAMING_SNAKE_CASE_ : int = 'vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE_ : str = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9} SCREAMING_SNAKE_CASE_ : List[str] = 'vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE_ : int = { 'visual_embedding_dim': 1_0_2_4, 'num_labels': 2, } SCREAMING_SNAKE_CASE_ : Optional[Any] = 'nlvr' SCREAMING_SNAKE_CASE_ : int = VisualBertConfig(**A__ ) # Load State Dict SCREAMING_SNAKE_CASE_ : List[str] = load_state_dict(A__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_new_dict(A__, A__ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE_ : Union[str, Any] = VisualBertForPreTraining(A__ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE_ : Dict = VisualBertForQuestionAnswering(A__ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE_ : Dict = VisualBertForVisualReasoning(A__ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE_ : Any = VisualBertForMultipleChoice(A__ ) model.load_state_dict(A__ ) # Save Checkpoints Path(A__ ).mkdir(exist_ok=A__ ) model.save_pretrained(A__ ) if __name__ == "__main__": lowerCAmelCase__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument('orig_checkpoint_path', type=str, help='A path to .th on local filesystem.') parser.add_argument('pytorch_dump_folder_path', type=str, help='Path to the output PyTorch model.') lowerCAmelCase__ : Dict =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
101
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
652
0
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , _A , _A=1_3 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=9_9 , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=1_6 , _A=2 , _A=0.02 , _A=False , _A=True , _A="None" , _A=3 , _A=4 , _A=None , ): '''simple docstring''' UpperCamelCase : Dict = parent UpperCamelCase : Dict = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : Any = is_training UpperCamelCase : int = use_input_mask UpperCamelCase : str = use_token_type_ids UpperCamelCase : int = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : List[str] = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Dict = hidden_act UpperCamelCase : str = hidden_dropout_prob UpperCamelCase : Dict = attention_probs_dropout_prob UpperCamelCase : Optional[Any] = max_position_embeddings UpperCamelCase : Dict = type_vocab_size UpperCamelCase : Optional[Any] = type_sequence_label_size UpperCamelCase : Tuple = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Optional[int] = num_choices UpperCamelCase : str = relative_attention UpperCamelCase : List[Any] = position_biased_input UpperCamelCase : Any = pos_att_type UpperCamelCase : Union[str, Any] = scope def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase : Optional[int] = None if self.use_token_type_ids: UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : int = None UpperCamelCase : Optional[Any] = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ): '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.get_config() UpperCamelCase : Union[str, Any] = 3_0_0 return config def _a ( self , _A ): '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def _a ( self , _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Union[str, Any] = DebertaModel(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Tuple = model(_A , attention_mask=_A , token_type_ids=_A )[0] UpperCamelCase : str = model(_A , token_type_ids=_A )[0] UpperCamelCase : Optional[Any] = model(_A )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def _a ( self , _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Optional[int] = DebertaForMaskedLM(config=_A ) model.to(_A ) model.eval() UpperCamelCase : int = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : int = self.num_labels UpperCamelCase : Union[str, Any] = DebertaForSequenceClassification(_A ) model.to(_A ) model.eval() UpperCamelCase : Optional[Any] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(_A ) def _a ( self , _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : Optional[int] = DebertaForTokenClassification(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Optional[Any] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , _A , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : List[Any] = DebertaForQuestionAnswering(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Optional[int] = model( _A , attention_mask=_A , token_type_ids=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ): '''simple docstring''' UpperCamelCase : str = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[str] = config_and_inputs UpperCamelCase : Any = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Optional[Any] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) __lowerCAmelCase : int = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase : Tuple = True __lowerCAmelCase : int = False __lowerCAmelCase : int = False __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : Tuple = False def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[int] = DebertaModelTester(self ) UpperCamelCase : Tuple = ConfigTester(self , config_class=_A , hidden_size=3_7 ) def _a ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*_A ) @slow def _a ( self ): '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : int = DebertaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch @require_sentencepiece @require_tokenizers class lowercase__ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""" ) def _a ( self ): '''simple docstring''' pass @slow def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[int] = DebertaModel.from_pretrained("""microsoft/deberta-base""" ) UpperCamelCase : Tuple = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) UpperCamelCase : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase : List[Any] = model(_A , attention_mask=_A )[0] # compare the actual values for a slice. UpperCamelCase : int = torch.tensor( [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
102
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a =logging.get_logger(__name__) # General docstring a ="""RegNetConfig""" # Base docstring a ="""facebook/regnet-y-040""" a =[1, 1088, 7, 7] # Image classification docstring a ="""facebook/regnet-y-040""" a ="""tabby, tabby cat""" a =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : Optional[str] = "relu" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2) __lowerCamelCase : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,strides=SCREAMING_SNAKE_CASE__ ,padding='VALID' ,groups=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution' ,) __lowerCamelCase : int = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') __lowerCamelCase : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Dict): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = config.num_channels __lowerCamelCase : Dict = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='embedder' ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__)[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,strides=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution') __lowerCamelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False): return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__) ,training=SCREAMING_SNAKE_CASE__) class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') __lowerCamelCase : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='relu' ,name='attention.0'), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='sigmoid' ,name='attention.2'), ] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__) for layer_module in self.attention: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = hidden_state * pooled return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[Any]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = max(1 ,out_channels // config.groups_width) __lowerCamelCase : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.2'), ] __lowerCamelCase : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : int = hidden_state for layer_module in self.layers: __lowerCamelCase : List[str] = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : int = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1 __lowerCamelCase : Tuple = max(1 ,out_channels // config.groups_width) __lowerCamelCase : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ ,reduced_channels=int(round(in_channels / 4)) ,name='layer.2'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.3'), ] __lowerCamelCase : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[int] = hidden_state for layer_module in self.layers: __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : Any = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCamelCase : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='layers.0'), *[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,name=F"layers.{i+1}") for i in range(depth - 1)], ] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): for layer_module in self.layers: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='stages.0' ,)) __lowerCamelCase : Optional[int] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:])): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__ ,name=F"stages.{i+1}")) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Optional[Any] = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__) @keras_serializable class A_ ( tf.keras.layers.Layer ): _UpperCAmelCase : List[Any] = RegNetConfig def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = config __lowerCamelCase : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ ,name='embedder') __lowerCamelCase : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ ,name='encoder') __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') @unpack_inputs def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,): __lowerCamelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = encoder_outputs[0] __lowerCamelCase : int = self.pooler(SCREAMING_SNAKE_CASE__) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) __lowerCamelCase : str = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) for h in encoder_outputs[1]]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : Optional[int] = '''regnet''' _UpperCAmelCase : List[Any] = '''pixel_values''' @property def lowerCAmelCase ( self : int): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) ,dtype=tf.floataa)} a =r""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : int=False ,): __lowerCamelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__ ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : str): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = config.num_labels __lowerCamelCase : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') # classification head __lowerCamelCase : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='classifier.1') if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Any=False ,): __lowerCamelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str = self.regnet( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states)
652
0
"""simple docstring""" import os def snake_case ( ) -> List[str]: with open(os.path.dirname(lowerCAmelCase_ ) + '''/grid.txt''' ) as f: _snake_case = [] # noqa: E741 for _ in range(20 ): l.append([int(lowerCAmelCase_ ) for x in f.readline().split()] ) _snake_case = 0 # right for i in range(20 ): for j in range(17 ): _snake_case = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: _snake_case = temp # down for i in range(17 ): for j in range(20 ): _snake_case = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: _snake_case = temp # diagonal 1 for i in range(17 ): for j in range(17 ): _snake_case = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: _snake_case = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): _snake_case = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: _snake_case = temp return maximum if __name__ == "__main__": print(solution())
103
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels a =object() # For specifying empty leaf dict `{}` a =object() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCamelCase__ ) - len(lowerCamelCase__ ) + 1 ): __lowerCamelCase : str = [x.match(lowerCamelCase__ ) for x, y in zip(lowerCamelCase__ , ks[i:] )] if matches and all(lowerCamelCase__ ): return True return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: def replace(lowerCamelCase__ , lowerCamelCase__ ): for rule, replacement in rules: if _match(lowerCamelCase__ , lowerCamelCase__ ): return replacement return val return replace def SCREAMING_SNAKE_CASE__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , lowerCamelCase__ )), (("transformer", "wte", "embedding"), P('mp' , lowerCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase__ , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCamelCase__ , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = _get_partition_rules() __lowerCamelCase : Optional[Any] = _replacement_rules(lowerCamelCase__ ) __lowerCamelCase : Tuple = {k: _unmatched for k in flatten_dict(lowerCamelCase__ )} __lowerCamelCase : List[Any] = {k: replace(lowerCamelCase__ , lowerCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCamelCase__ ) )
652
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = { """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """LILT_PRETRAINED_MODEL_ARCHIVE_LIST""", """LiltForQuestionAnswering""", """LiltForSequenceClassification""", """LiltForTokenClassification""", """LiltModel""", """LiltPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
104
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list: __lowerCamelCase : Union[str, Any] = [True] * n __lowerCamelCase : List[Any] = False __lowerCamelCase : int = False __lowerCamelCase : Any = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __lowerCamelCase : List[str] = i * 2 while index < n: __lowerCamelCase : Optional[int] = False __lowerCamelCase : List[Any] = index + i __lowerCamelCase : Optional[Any] = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 9_9_9_9_6_6_6_6_3_3_3_3 ) -> int: __lowerCamelCase : Optional[Any] = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_0_0 __lowerCamelCase : Dict = prime_sieve(lowerCamelCase__ ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Any = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase : Any = primes[prime_index + 1] __lowerCamelCase : Optional[Any] = last_prime**2 __lowerCamelCase : Dict = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase : Tuple = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase : List[Any] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
652
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ : Dict = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Any = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Dict = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : str = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys UpperCamelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
105
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = 1 @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.15 ,SCREAMING_SNAKE_CASE__ : float = 0.01 ,SCREAMING_SNAKE_CASE__ : float = 1348.0 ,SCREAMING_SNAKE_CASE__ : float = 1E-5 ,SCREAMING_SNAKE_CASE__ : int = 1 ,): # standard deviation of the initial noise distribution __lowerCamelCase : int = sigma_max # setable values __lowerCamelCase : List[str] = None self.set_sigmas(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps __lowerCamelCase : Optional[int] = torch.linspace(1 ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,device=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None): __lowerCamelCase : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __lowerCamelCase : Optional[int] = sigma_max if sigma_max is not None else self.config.sigma_max __lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __lowerCamelCase : Optional[Any] = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__) ,math.log(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str]): return torch.where( timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') __lowerCamelCase : List[str] = timestep * torch.ones( sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) __lowerCamelCase : str = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __lowerCamelCase : Dict = timesteps.to(self.discrete_sigmas.device) __lowerCamelCase : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device) __lowerCamelCase : Optional[Any] = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).to(sample.device) __lowerCamelCase : int = torch.zeros_like(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __lowerCamelCase : int = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): __lowerCamelCase : List[Any] = diffusion.unsqueeze(-1) __lowerCamelCase : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __lowerCamelCase : int = randn_tensor( sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__ ,device=sample.device ,dtype=sample.dtype) __lowerCamelCase : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __lowerCamelCase : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,prev_sample_mean=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __lowerCamelCase : Optional[int] = randn_tensor(sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__).to(sample.device) # compute step size from the model_output, the noise, and the snr __lowerCamelCase : str = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __lowerCamelCase : Optional[int] = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): __lowerCamelCase : List[str] = step_size.unsqueeze(-1) __lowerCamelCase : str = sample + step_size * model_output __lowerCamelCase : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,): # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase : int = timesteps.to(original_samples.device) __lowerCamelCase : Any = self.discrete_sigmas.to(original_samples.device)[timesteps] __lowerCamelCase : Optional[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__) * sigmas[:, None, None, None] ) __lowerCamelCase : str = noise + original_samples return noisy_samples def __len__( self : Optional[int]): return self.config.num_train_timesteps
652
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case :Union[str, Any] =logging.get_logger(__name__) __snake_case :Dict ={ 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json', 'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json', 'cl-tohoku/bert-base-japanese-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json' ), 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json', # See all BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase__ ( _lowerCamelCase ): A_ : List[Any] = 'bert' def __init__( self : Union[str, Any] , __UpperCamelCase : int=30_522 , __UpperCamelCase : Union[str, Any]=768 , __UpperCamelCase : Optional[Any]=12 , __UpperCamelCase : Any=12 , __UpperCamelCase : Dict=3_072 , __UpperCamelCase : Any="gelu" , __UpperCamelCase : str=0.1 , __UpperCamelCase : str=0.1 , __UpperCamelCase : str=512 , __UpperCamelCase : str=2 , __UpperCamelCase : Union[str, Any]=0.0_2 , __UpperCamelCase : int=1e-12 , __UpperCamelCase : Union[str, Any]=0 , __UpperCamelCase : Any="absolute" , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : str=None , **__UpperCamelCase : int , ) -> Optional[Any]: super().__init__(pad_token_id=__UpperCamelCase , **__UpperCamelCase ) A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = position_embedding_type A = use_cache A = classifier_dropout class lowerCAmelCase__ ( _lowerCamelCase ): @property def __UpperCamelCase ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
106
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' import sys _UpperCAmelCase : Optional[int] = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def _SCREAMING_SNAKE_CASE ( __snake_case : str = N ): _A = -sys.maxsize - 1 for i in range(len(__snake_case ) - 1_2 ): _A = 1 for j in range(1_3 ): product *= int(n[i + j] ) if product > largest_product: _A = product return largest_product if __name__ == "__main__": print(F'''{solution() = }''')
107
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : Optional[int] = [file for file in files if n_ not in file] else: __lowerCamelCase : Dict = [file for file in files if n_identifier not in file] __lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : Optional[int] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : int = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = 'modeling' __lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = Path('src/transformers') __lowerCamelCase : Optional[int] = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : str = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = Path('docs/source') __lowerCamelCase : str = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
652
0
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 SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _lowerCamelCase = ['''pixel_values'''] def __init__( self : Optional[int] , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = True , **lowerCamelCase : Optional[int] , ) -> None: """simple docstring""" super().__init__(**lowerCamelCase ) _UpperCAmelCase = size if size is not None else {"""shortest_edge""": 224} _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) _UpperCAmelCase = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="""crop_size""" ) _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = resample _UpperCAmelCase = do_center_crop _UpperCAmelCase = crop_size _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _UpperCAmelCase = image_std if image_std is not None else OPENAI_CLIP_STD _UpperCAmelCase = do_convert_rgb def lowerCamelCase ( self : List[str] , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Dict , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _UpperCAmelCase = get_resize_output_image_size(lowerCamelCase , size=size["""shortest_edge"""] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Dict , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["""height"""], size["""width"""]) , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : Optional[int] , lowerCamelCase : np.ndarray , lowerCamelCase : Union[int, float] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Dict , ) -> Optional[int]: """simple docstring""" return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : List[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Any , ) -> np.ndarray: """simple docstring""" return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : List[str] , lowerCamelCase : ImageInput , lowerCamelCase : bool = None , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = None , lowerCamelCase : bool = None , lowerCamelCase : int = None , lowerCamelCase : bool = None , lowerCamelCase : float = None , lowerCamelCase : bool = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : Any , ) -> PIL.Image.Image: """simple docstring""" _UpperCAmelCase = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase = size if size is not None else self.size _UpperCAmelCase = get_size_dict(lowerCamelCase , param_name="""size""" , default_to_square=lowerCamelCase ) _UpperCAmelCase = resample if resample is not None else self.resample _UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCAmelCase = crop_size if crop_size is not None else self.crop_size _UpperCAmelCase = get_size_dict(lowerCamelCase , param_name="""crop_size""" , default_to_square=lowerCamelCase ) _UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase = image_mean if image_mean is not None else self.image_mean _UpperCAmelCase = image_std if image_std is not None else self.image_std _UpperCAmelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _UpperCAmelCase = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: _UpperCAmelCase = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. _UpperCAmelCase = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: _UpperCAmelCase = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: _UpperCAmelCase = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: _UpperCAmelCase = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: _UpperCAmelCase = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] _UpperCAmelCase = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] _UpperCAmelCase = {"""pixel_values""": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
108
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} a ={ """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } a ={"""vinai/bartpho-syllable""": 1024} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Any="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="<s>" ,SCREAMING_SNAKE_CASE__ : int="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<mask>" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = vocab_file __lowerCamelCase : Tuple = monolingual_vocab_file __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__)) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Any = cnt cnt += 1 with open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for line in f.readlines(): __lowerCamelCase : Any = line.strip().split()[0] __lowerCamelCase : List[str] = len(self.fairseq_tokens_to_ids) if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Dict = len(self.fairseq_tokens_to_ids) __lowerCamelCase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): __lowerCamelCase : Tuple = self.__dict__.copy() __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : str = {} __lowerCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Tuple = [self.cls_token_id] __lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Dict = [self.sep_token_id] __lowerCamelCase : 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 lowerCAmelCase ( self : List[str]): return len(self.fairseq_ids_to_tokens) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): return self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Any = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( SCREAMING_SNAKE_CASE__) and os.path.isfile(self.monolingual_vocab_file): copyfile(self.monolingual_vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.monolingual_vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(SCREAMING_SNAKE_CASE__)} \n") return out_vocab_file, out_monolingual_vocab_file
652
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor a = logging.get_logger(__name__) class __a ( _snake_case ): def __init__( self : List[str] ,*lowerCamelCase : Optional[Any] ,**lowerCamelCase : int ): '''simple docstring''' warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" ,lowerCamelCase ,) super().__init__(*lowerCamelCase ,**lowerCamelCase )
109
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_3 ,SCREAMING_SNAKE_CASE__ : int=3_0 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=3_2 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2 ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Dict = image_size __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = is_training __lowerCamelCase : List[Any] = use_labels __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : List[str] = scope __lowerCamelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCamelCase : str = (image_size // patch_size) ** 2 __lowerCamelCase : str = num_patches + 2 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : List[Any] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any]): return DeiTConfig( 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=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Optional[Any] = TFDeiTModel(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCamelCase : int = 1 __lowerCamelCase : Tuple = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.type_sequence_label_size __lowerCamelCase : List[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = config_and_inputs __lowerCamelCase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _UpperCAmelCase : List[Any] = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = TFDeiTModelTester(self) __lowerCamelCase : Optional[int] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : str): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,tf.keras.layers.Dense)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Any = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=False): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224') __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : Tuple = prepare_img() __lowerCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='tf') # forward pass __lowerCamelCase : int = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tf.constant([-1.0266, 0.1912, -1.2861]) self.assertTrue(np.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
652
0
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , UpperCamelCase , UpperCamelCase=7 , UpperCamelCase=3 , UpperCamelCase=18 , UpperCamelCase=30 , UpperCamelCase=4_00 , UpperCamelCase=True , UpperCamelCase=None , UpperCamelCase=True , UpperCamelCase=None , UpperCamelCase=True , UpperCamelCase=[0.5, 0.5, 0.5] , UpperCamelCase=[0.5, 0.5, 0.5] , UpperCamelCase=False , ) -> List[str]: UpperCamelCase__ : int = size if size is not None else {'height': 20, 'width': 20} UpperCamelCase__ : Tuple = crop_size if crop_size is not None else {'height': 18, 'width': 18} UpperCamelCase__ : Optional[int] = parent UpperCamelCase__ : List[str] = batch_size UpperCamelCase__ : Tuple = num_channels UpperCamelCase__ : Tuple = image_size UpperCamelCase__ : Optional[int] = min_resolution UpperCamelCase__ : Optional[int] = max_resolution UpperCamelCase__ : int = do_resize UpperCamelCase__ : int = size UpperCamelCase__ : int = do_center_crop UpperCamelCase__ : Tuple = crop_size UpperCamelCase__ : List[Any] = do_normalize UpperCamelCase__ : Tuple = image_mean UpperCamelCase__ : Union[str, Any] = image_std UpperCamelCase__ : Dict = do_reduce_labels def lowerCAmelCase__ ( self) -> Optional[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _lowercase ( ) -> Optional[int]: UpperCamelCase__ : Tuple = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) UpperCamelCase__ : Optional[int] = Image.open(dataset[0]['file'] ) UpperCamelCase__ : Any = Image.open(dataset[1]['file'] ) return image, map def _lowercase ( ) -> Optional[int]: UpperCamelCase__ : str = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) UpperCamelCase__ : Union[str, Any] = Image.open(ds[0]['file'] ) UpperCamelCase__ : Any = Image.open(ds[1]['file'] ) UpperCamelCase__ : List[str] = Image.open(ds[2]['file'] ) UpperCamelCase__ : Optional[int] = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCamelCase_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ = BeitImageProcessor if is_vision_available() else None def lowerCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase__ : Optional[int] = BeitImageProcessingTester(self) @property def lowerCAmelCase__ ( self) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase__ ( self) -> Tuple: UpperCamelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_center_crop')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'center_crop')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std')) def lowerCAmelCase__ ( self) -> Optional[Any]: UpperCamelCase__ : str = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 20, 'width': 20}) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18}) self.assertEqual(image_processor.do_reduce_labels , SCREAMING_SNAKE_CASE__) UpperCamelCase__ : int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=SCREAMING_SNAKE_CASE__) self.assertEqual(image_processor.size , {'height': 42, 'width': 42}) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84}) self.assertEqual(image_processor.do_reduce_labels , SCREAMING_SNAKE_CASE__) def lowerCAmelCase__ ( self) -> List[Any]: pass def lowerCAmelCase__ ( self) -> Union[str, Any]: # Initialize image_processing UpperCamelCase__ : Any = self.image_processing_class(**self.image_processor_dict) # create random PIL images UpperCamelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image) # Test not batched input UpperCamelCase__ : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase__ : Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def lowerCAmelCase__ ( self) -> List[Any]: # Initialize image_processing UpperCamelCase__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors UpperCamelCase__ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray) # Test not batched input UpperCamelCase__ : Dict = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase__ : List[str] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def lowerCAmelCase__ ( self) -> Union[str, Any]: # Initialize image_processing UpperCamelCase__ : Dict = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors UpperCamelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor) # Test not batched input UpperCamelCase__ : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase__ : List[str] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def lowerCAmelCase__ ( self) -> int: # Initialize image_processing UpperCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors UpperCamelCase__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__) UpperCamelCase__ : List[Any] = [] for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor) maps.append(torch.zeros(image.shape[-2:]).long()) # Test not batched input UpperCamelCase__ : Tuple = image_processing(image_inputs[0] , maps[0] , return_tensors='pt') self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long) self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 2_55) # Test batched UpperCamelCase__ : int = image_processing(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt') self.assertEqual( encoding['pixel_values'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long) self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 2_55) # Test not batched input (PIL images) UpperCamelCase__ : Tuple = prepare_semantic_single_inputs() UpperCamelCase__ : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt') self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long) self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 2_55) # Test batched input (PIL images) UpperCamelCase__ : Optional[Any] = prepare_semantic_batch_inputs() UpperCamelCase__ : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt') self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long) self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 2_55) def lowerCAmelCase__ ( self) -> str: # Initialize image_processing UpperCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 UpperCamelCase__ : Tuple = prepare_semantic_single_inputs() UpperCamelCase__ : Union[str, Any] = image_processing(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt') self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 1_50) UpperCamelCase__ : Tuple = True UpperCamelCase__ : Optional[Any] = image_processing(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt') self.assertTrue(encoding['labels'].min().item() >= 0) self.assertTrue(encoding['labels'].max().item() <= 2_55)
410
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] _UpperCAmelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
652
0
'''simple docstring''' from math import factorial def lowerCAmelCase__ ( lowerCamelCase : Any = 20 ): _A : List[Any] = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... _A : List[Any] = n // 2 return int(factorial(lowerCamelCase__ ) / (factorial(lowerCamelCase__ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: A : str = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number.''')
128
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
652
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __snake_case : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Any = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys __snake_case : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
571
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """vocab.txt"""} a ={ """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } a ={ """openbmb/cpm-ant-10b""": 1024, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: __lowerCamelCase : int = collections.OrderedDict() with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as reader: __lowerCamelCase : Optional[int] = reader.readlines() for index, token in enumerate(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = token.rstrip('\n' ) __lowerCamelCase : Union[str, Any] = index return vocab class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[int]="<unk>" ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_0): __lowerCamelCase : str = vocab __lowerCamelCase : Dict = unk_token __lowerCamelCase : int = max_input_chars_per_word def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > self.max_input_chars_per_word: return [self.unk_token] __lowerCamelCase : Tuple = 0 __lowerCamelCase : str = [] while start < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = None while start < end: __lowerCamelCase : Any = ''.join(chars[start:end]) if substr in self.vocab: __lowerCamelCase : Optional[Any] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = end return sub_tokens class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = ['''input_ids''', '''attention_mask'''] _UpperCAmelCase : Optional[int] = False def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple="<d>" ,SCREAMING_SNAKE_CASE__ : Tuple="</d>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="</s>" ,SCREAMING_SNAKE_CASE__ : str="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<unk>" ,SCREAMING_SNAKE_CASE__ : List[Any]="</n>" ,SCREAMING_SNAKE_CASE__ : int="</_>" ,SCREAMING_SNAKE_CASE__ : List[Any]="left" ,**SCREAMING_SNAKE_CASE__ : List[str] ,): requires_backends(self ,['jieba']) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ ,eod_token=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,line_token=SCREAMING_SNAKE_CASE__ ,space_token=SCREAMING_SNAKE_CASE__ ,padding_side=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Optional[Any] = bod_token __lowerCamelCase : Dict = eod_token __lowerCamelCase : Any = load_vocab(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.encoder[space_token] __lowerCamelCase : Dict = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __lowerCamelCase : Optional[Any] = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) __lowerCamelCase : int = {v: k for k, v in self.encoder.items()} __lowerCamelCase : Union[str, Any] = WordpieceTokenizer(vocab=self.encoder ,unk_token=self.unk_token) @property def lowerCAmelCase ( self : List[Any]): return self.encoder[self.bod_token] @property def lowerCAmelCase ( self : Tuple): return self.encoder[self.eod_token] @property def lowerCAmelCase ( self : Union[str, Any]): return self.encoder["\n"] @property def lowerCAmelCase ( self : str): return len(self.encoder) def lowerCAmelCase ( self : str): return dict(self.encoder ,**self.added_tokens_encoder) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Any = [] for x in jieba.cut(SCREAMING_SNAKE_CASE__ ,cut_all=SCREAMING_SNAKE_CASE__): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__)) return output_tokens def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Tuple = [i for i in token_ids if i >= 0] __lowerCamelCase : str = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[Any]): return token in self.encoder def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.encoder.get(SCREAMING_SNAKE_CASE__ ,self.encoder.get(self.unk_token)) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.decoder.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : int = (filename_prefix + '-' if filename_prefix else '') + save_directory __lowerCamelCase : Any = 0 if " " in self.encoder: __lowerCamelCase : Any = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: __lowerCamelCase : str = self.encoder['\n'] del self.encoder["\n"] __lowerCamelCase : str = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Any = token_index writer.write(token + '\n') index += 1 return (vocab_file,) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : List[int] = None): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__))
652
0
'''simple docstring''' import math def UpperCamelCase ( _lowerCamelCase : Optional[int] ): A__ = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCamelCase__ ) def UpperCamelCase ( _lowerCamelCase : Union[str, Any] = 1 / 1_23_45 ): A__ = 0 A__ = 0 A__ = 3 while True: A__ = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCamelCase__ ): A__ = int(lowerCamelCase__ ) total_partitions += 1 if check_partition_perfect(lowerCamelCase__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCamelCase__ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
440
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a ={"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
652
0
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __UpperCAmelCase = 16 __UpperCAmelCase = 32 def snake_case_ (__A : Union[str, Any] , __A : Union[str, Any] , __A : int , __A : str , __A : int = 1_6 ) -> Union[str, Any]: __lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __lowerCAmelCase : Union[str, Any] = DatasetDict( { """train""": dataset["""train"""].select(lowerCamelCase__ ), """validation""": dataset["""train"""].select(lowerCamelCase__ ), """test""": dataset["""validation"""], } ) def tokenize_function(__A : Tuple ): # max_length=None => use the model max length (it's actually the default) __lowerCAmelCase : Optional[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCamelCase__ , max_length=lowerCamelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __lowerCAmelCase : 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 __lowerCAmelCase : Optional[int] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__A : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. __lowerCAmelCase : Any = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __lowerCAmelCase : Any = 1_6 elif accelerator.mixed_precision != "no": __lowerCAmelCase : Any = 8 else: __lowerCAmelCase : str = None return tokenizer.pad( lowerCamelCase__ , padding="""longest""" , max_length=lowerCamelCase__ , pad_to_multiple_of=lowerCamelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. __lowerCAmelCase : int = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCamelCase__ , collate_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ ) __lowerCAmelCase : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCamelCase__ , collate_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ ) __lowerCAmelCase : Dict = DataLoader( tokenized_datasets["""test"""] , shuffle=lowerCamelCase__ , collate_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ ) return train_dataloader, eval_dataloader, test_dataloader def snake_case_ (__A : str , __A : Tuple ) -> List[str]: # New Code # __lowerCAmelCase : str = [] # Download the dataset __lowerCAmelCase : Any = load_dataset("""glue""" , """mrpc""" ) # Create our splits __lowerCAmelCase : int = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator __lowerCAmelCase : List[str] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCAmelCase : Optional[Any] = config['lr'] __lowerCAmelCase : str = int(config["""num_epochs"""] ) __lowerCAmelCase : Optional[Any] = int(config["""seed"""] ) __lowerCAmelCase : List[Any] = int(config["""batch_size"""] ) __lowerCAmelCase : Union[str, Any] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation __lowerCAmelCase : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __lowerCAmelCase : Dict = batch_size // MAX_GPU_BATCH_SIZE __lowerCAmelCase : Optional[int] = MAX_GPU_BATCH_SIZE set_seed(lowerCamelCase__ ) # New Code # # Create our folds: __lowerCAmelCase : Union[str, Any] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) __lowerCAmelCase : Tuple = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(lowerCamelCase__ ): __lowerCAmelCase : int = get_fold_dataloaders( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCAmelCase : Optional[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). __lowerCAmelCase : List[Any] = model.to(accelerator.device ) # Instantiate optimizer __lowerCAmelCase : Union[str, Any] = AdamW(params=model.parameters() , lr=lowerCamelCase__ ) # Instantiate scheduler __lowerCAmelCase : List[Any] = get_linear_schedule_with_warmup( optimizer=lowerCamelCase__ , num_warmup_steps=1_0_0 , num_training_steps=(len(lowerCamelCase__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __lowerCAmelCase : 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 ) __lowerCAmelCase : Union[str, Any] = model(**lowerCamelCase__ ) __lowerCAmelCase : List[Any] = outputs.loss __lowerCAmelCase : str = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __lowerCAmelCase : List[Any] = model(**lowerCamelCase__ ) __lowerCAmelCase : Union[str, Any] = outputs.logits.argmax(dim=-1 ) __lowerCAmelCase : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=lowerCamelCase__ , references=lowerCamelCase__ , ) __lowerCAmelCase : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCamelCase__ ) # New Code # # We also run predictions on the test set at the very end __lowerCAmelCase : int = [] for step, batch in enumerate(lowerCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model(**lowerCamelCase__ ) __lowerCAmelCase : List[str] = outputs.logits __lowerCAmelCase : Dict = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(lowerCamelCase__ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: __lowerCAmelCase : Optional[int] = torch.cat(lowerCamelCase__ , dim=0 ) __lowerCAmelCase : List[Any] = torch.stack(lowerCamelCase__ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) __lowerCAmelCase : Optional[int] = metric.compute(predictions=lowerCamelCase__ , references=lowerCamelCase__ ) accelerator.print("""Average test metrics from all folds:""" , lowerCamelCase__ ) def snake_case_ () -> Dict: __lowerCAmelCase : int = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=lowerCamelCase__ , default=lowerCamelCase__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=lowerCamelCase__ , default=3 , help="""The number of splits to perform across the dataset""" ) __lowerCAmelCase : str = parser.parse_args() __lowerCAmelCase : Optional[Any] = {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6} training_function(lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": main()
651
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = (UnCLIPScheduler,) def lowerCAmelCase ( self : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Any = { 'num_train_timesteps': 1_0_0_0, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**SCREAMING_SNAKE_CASE__) return config def lowerCAmelCase ( self : Optional[Any]): for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any]): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): for clip_sample_range in [1, 5, 1_0, 2_0]: self.check_over_configs(clip_sample_range=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any]): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): for time_step in [0, 5_0_0, 9_9_9]: for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Any = self.get_scheduler_config(variance_type='fixed_small_log') __lowerCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE__) assert torch.sum(torch.abs(scheduler._get_variance(0) - 1.00_00E-10)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7) - 0.0549625)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9) - 0.9994987)) < 1E-5 def lowerCAmelCase ( self : Any): __lowerCamelCase : Dict = self.scheduler_classes[0] __lowerCamelCase : List[str] = self.get_scheduler_config(variance_type='learned_range') __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = 0.5 assert scheduler._get_variance(1 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -10.1712790 < 1E-5 assert scheduler._get_variance(4_8_7 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -5.7998052 < 1E-5 assert scheduler._get_variance(9_9_9 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -0.0010011 < 1E-5 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : str = self.get_scheduler_config() __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = scheduler.timesteps __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter __lowerCamelCase : List[str] = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : int = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # 2. predict previous mean of sample x_t-1 __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Optional[Any] = pred_prev_sample __lowerCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 252.2682495) < 1E-2 assert abs(result_mean.item() - 0.3284743) < 1E-3 def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : List[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(2_5) __lowerCamelCase : int = scheduler.timesteps __lowerCamelCase : Tuple = self.dummy_model() __lowerCamelCase : Any = self.dummy_sample_deter __lowerCamelCase : Any = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if i + 1 == timesteps.shape[0]: __lowerCamelCase : Optional[Any] = None else: __lowerCamelCase : Union[str, Any] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __lowerCamelCase : int = scheduler.step( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Union[str, Any] = pred_prev_sample __lowerCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 258.2044983) < 1E-2 assert abs(result_mean.item() - 0.3362038) < 1E-3 def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Union[str, Any]): pass
652
0
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): '''simple docstring''' def _lowerCamelCase ( self : Optional[Any] ) -> int: _lowercase : Any = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'tf_padding' ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'depth_multiplier' ) ) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Dict ,UpperCamelCase : Optional[Any] ,UpperCamelCase : List[Any]=13 ,UpperCamelCase : str=3 ,UpperCamelCase : Dict=32 ,UpperCamelCase : Optional[int]=0.2_5 ,UpperCamelCase : Optional[Any]=8 ,UpperCamelCase : Optional[Any]=True ,UpperCamelCase : int=1024 ,UpperCamelCase : Optional[int]=32 ,UpperCamelCase : Any="relu6" ,UpperCamelCase : Optional[int]=0.1 ,UpperCamelCase : List[Any]=0.0_2 ,UpperCamelCase : str=True ,UpperCamelCase : str=True ,UpperCamelCase : Dict=10 ,UpperCamelCase : int=None ,) -> Tuple: _lowercase : Optional[int] = parent _lowercase : Union[str, Any] = batch_size _lowercase : Optional[Any] = num_channels _lowercase : Any = image_size _lowercase : Tuple = depth_multiplier _lowercase : Any = min_depth _lowercase : Union[str, Any] = tf_padding _lowercase : Dict = int(last_hidden_size * depth_multiplier ) _lowercase : Union[str, Any] = output_stride _lowercase : Optional[Any] = hidden_act _lowercase : str = classifier_dropout_prob _lowercase : Tuple = use_labels _lowercase : str = is_training _lowercase : Optional[Any] = num_labels _lowercase : List[str] = initializer_range _lowercase : List[str] = scope def _lowerCamelCase ( self : List[Any] ) -> Any: _lowercase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowercase : Any = None _lowercase : int = None if self.use_labels: _lowercase : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _lowercase : str = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) _lowercase : Any = self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCamelCase ( self : Optional[int] ) -> List[str]: return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def _lowerCamelCase ( self : List[Any] ,UpperCamelCase : Optional[int] ,UpperCamelCase : str ,UpperCamelCase : List[Any] ,UpperCamelCase : Optional[int] ) -> List[Any]: _lowercase : Optional[int] = MobileNetVaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() _lowercase : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def _lowerCamelCase ( self : str ,UpperCamelCase : str ,UpperCamelCase : Union[str, Any] ,UpperCamelCase : Optional[Any] ,UpperCamelCase : Optional[Any] ) -> Any: _lowercase : List[Any] = self.num_labels _lowercase : Optional[int] = MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() _lowercase : Dict = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCamelCase ( self : Any ) -> Optional[int]: _lowercase : int = self.prepare_config_and_inputs() _lowercase : Tuple = config_and_inputs _lowercase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Any = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowerCAmelCase__ : Union[str, Any] = ( {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase__ : Dict = False lowerCAmelCase__ : List[str] = False lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : Dict = False def _lowerCamelCase ( self : List[str] ) -> Union[str, Any]: _lowercase : Union[str, Any] = MobileNetVaModelTester(self ) _lowercase : Union[str, Any] = MobileNetVaConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ) def _lowerCamelCase ( self : List[str] ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV1 does not use inputs_embeds' ) def _lowerCamelCase ( self : Optional[int] ) -> Any: pass @unittest.skip(reason='MobileNetV1 does not support input and output embeddings' ) def _lowerCamelCase ( self : Any ) -> List[str]: pass @unittest.skip(reason='MobileNetV1 does not output attentions' ) def _lowerCamelCase ( self : Union[str, Any] ) -> List[str]: pass def _lowerCamelCase ( self : str ) -> Optional[int]: _lowercase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : int = model_class(SCREAMING_SNAKE_CASE__ ) _lowercase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : Tuple = [*signature.parameters.keys()] _lowercase : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__ ) def _lowerCamelCase ( self : Dict ) -> str: _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _lowerCamelCase ( self : Dict ) -> Union[str, Any]: def check_hidden_states_output(UpperCamelCase : List[Any] ,UpperCamelCase : str ,UpperCamelCase : Any ): _lowercase : Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): _lowercase : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ) _lowercase : Optional[Any] = outputs.hidden_states _lowercase : Union[str, Any] = 26 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) ,SCREAMING_SNAKE_CASE__ ) _lowercase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : Any = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowercase : str = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _lowerCamelCase ( self : Dict ) -> List[Any]: _lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def _lowerCamelCase ( self : int ) -> Tuple: for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : int = MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: '''simple docstring''' _lowercase : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _lowerCamelCase ( self : Any ) -> Optional[int]: return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224' ) if is_vision_available() else None ) @slow def _lowerCamelCase ( self : int ) -> Optional[Any]: _lowercase : List[Any] = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224' ).to(SCREAMING_SNAKE_CASE__ ) _lowercase : Dict = self.default_image_processor _lowercase : Optional[int] = prepare_img() _lowercase : str = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='pt' ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): _lowercase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits _lowercase : int = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__ ) _lowercase : Optional[int] = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1e-4 ) )
125
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''swin2sr''' _UpperCAmelCase : Any = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=1 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : Tuple=1_8_0 ,SCREAMING_SNAKE_CASE__ : Any=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : int=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=8 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2.0 ,SCREAMING_SNAKE_CASE__ : Optional[int]=True ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-5 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Tuple=1.0 ,SCREAMING_SNAKE_CASE__ : int="1conv" ,SCREAMING_SNAKE_CASE__ : Optional[int]="pixelshuffle" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = image_size __lowerCamelCase : str = patch_size __lowerCamelCase : List[Any] = num_channels __lowerCamelCase : Dict = embed_dim __lowerCamelCase : Dict = depths __lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = num_heads __lowerCamelCase : Tuple = window_size __lowerCamelCase : Dict = mlp_ratio __lowerCamelCase : str = qkv_bias __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[Any] = attention_probs_dropout_prob __lowerCamelCase : List[Any] = drop_path_rate __lowerCamelCase : Optional[int] = hidden_act __lowerCamelCase : Dict = use_absolute_embeddings __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : str = initializer_range __lowerCamelCase : List[Any] = upscale __lowerCamelCase : List[Any] = img_range __lowerCamelCase : List[str] = resi_connection __lowerCamelCase : Union[str, Any] = upsampler
652
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", }, "tokenizer_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE = { "albert-base-v1": 5_12, "albert-large-v1": 5_12, "albert-xlarge-v1": 5_12, "albert-xxlarge-v1": 5_12, "albert-base-v2": 5_12, "albert-large-v2": 5_12, "albert-xlarge-v2": 5_12, "albert-xxlarge-v2": 5_12, } _SCREAMING_SNAKE_CASE = "▁" class SCREAMING_SNAKE_CASE_ ( _a ): """simple docstring""" __lowerCAmelCase : Optional[Any] =VOCAB_FILES_NAMES __lowerCAmelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase : Tuple =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase : Optional[int] =AlbertTokenizer def __init__( self :Dict, snake_case :Dict=None, snake_case :Any=None, snake_case :Tuple=True, snake_case :str=True, snake_case :Tuple=False, snake_case :Tuple="[CLS]", snake_case :Tuple="[SEP]", snake_case :List[Any]="<unk>", snake_case :List[str]="[SEP]", snake_case :Optional[Any]="<pad>", snake_case :Any="[CLS]", snake_case :str="[MASK]", **snake_case :int, ): """simple docstring""" _lowercase =( AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__, normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__) else mask_token ) super().__init__( SCREAMING_SNAKE_CASE__, tokenizer_file=SCREAMING_SNAKE_CASE__, do_lower_case=SCREAMING_SNAKE_CASE__, remove_space=SCREAMING_SNAKE_CASE__, keep_accents=SCREAMING_SNAKE_CASE__, bos_token=SCREAMING_SNAKE_CASE__, eos_token=SCREAMING_SNAKE_CASE__, unk_token=SCREAMING_SNAKE_CASE__, sep_token=SCREAMING_SNAKE_CASE__, pad_token=SCREAMING_SNAKE_CASE__, cls_token=SCREAMING_SNAKE_CASE__, mask_token=SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__, ) _lowercase =do_lower_case _lowercase =remove_space _lowercase =keep_accents _lowercase =vocab_file _lowercase =False if not self.vocab_file else True def UpperCamelCase__ ( self :str, snake_case :List[int], snake_case :Optional[List[int]] = None): """simple docstring""" _lowercase =[self.sep_token_id] _lowercase =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase__ ( self :Tuple, snake_case :List[int], snake_case :Optional[List[int]] = None): """simple docstring""" _lowercase =[self.sep_token_id] _lowercase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def UpperCamelCase__ ( self :int, snake_case :str, snake_case :Optional[str] = None): """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.') if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''') return _lowercase =os.path.join( SCREAMING_SNAKE_CASE__, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__): copyfile(self.vocab_file, SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
181
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__="pt" ) -> Dict: __lowerCamelCase : Any = {'add_prefix_space': True} if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not line.startswith(' ' ) else {} __lowerCamelCase : int = padding_side return tokenizer( [line] , max_length=lowerCamelCase__ , padding='max_length' if pad_to_max_length else None , truncation=lowerCamelCase__ , return_tensors=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , ) -> List[str]: __lowerCamelCase : List[str] = input_ids.ne(lowerCamelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]="train" ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[Any]="" ,): super().__init__() __lowerCamelCase : Optional[Any] = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.source') __lowerCamelCase : Any = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.target') __lowerCamelCase : List[Any] = self.get_char_lens(self.src_file) __lowerCamelCase : List[Any] = max_source_length __lowerCamelCase : List[str] = max_target_length assert min(self.src_lens) > 0, F"found empty line in {self.src_file}" __lowerCamelCase : Any = tokenizer __lowerCamelCase : Optional[int] = prefix if n_obs is not None: __lowerCamelCase : Dict = self.src_lens[:n_obs] __lowerCamelCase : str = src_lang __lowerCamelCase : Any = tgt_lang def __len__( self : Tuple): return len(self.src_lens) def __getitem__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Dict = index + 1 # linecache starts at 1 __lowerCamelCase : Any = self.prefix + linecache.getline(str(self.src_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') __lowerCamelCase : int = linecache.getline(str(self.tgt_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __lowerCamelCase : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer ) __lowerCamelCase : Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer __lowerCamelCase : List[str] = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_source_length ,'right') __lowerCamelCase : Any = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_target_length ,'right') __lowerCamelCase : List[Any] = source_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = target_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : int): return [len(SCREAMING_SNAKE_CASE__) for x in Path(SCREAMING_SNAKE_CASE__).open().readlines()] def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[Any] = torch.stack([x['input_ids'] for x in batch]) __lowerCamelCase : Any = torch.stack([x['attention_mask'] for x in batch]) __lowerCamelCase : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch]) __lowerCamelCase : Optional[int] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch a =getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return list(itertools.chain.from_iterable(lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: __lowerCamelCase : str = get_git_info() save_json(lowerCamelCase__ , os.path.join(lowerCamelCase__ , 'git_log.json' ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=4 , **lowerCamelCase__ ) -> List[str]: with open(lowerCamelCase__ , 'w' ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=lowerCamelCase__ , **lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: with open(lowerCamelCase__ ) as f: return json.load(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: __lowerCamelCase : str = git.Repo(search_parent_directories=lowerCamelCase__ ) __lowerCamelCase : Any = { 'repo_id': str(lowerCamelCase__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List: return list(map(lowerCamelCase__ , lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: with open(lowerCamelCase__ , 'wb' ) as f: return pickle.dump(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: def remove_articles(lowerCamelCase__ ): return re.sub(R'\b(a|an|the)\b' , ' ' , lowerCamelCase__ ) def white_space_fix(lowerCamelCase__ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase__ ): __lowerCamelCase : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : str = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Optional[int] = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) & Counter(lowerCamelCase__ ) __lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 __lowerCamelCase : List[Any] = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : int = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: return normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) __lowerCamelCase : Dict = 0 for hypo, pred in zip(lowerCamelCase__ , lowerCamelCase__ ): em += exact_match_score(lowerCamelCase__ , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: em /= len(lowerCamelCase__ ) return {"em": em} def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return model_prefix.startswith('rag' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __lowerCamelCase : List[str] = 'dropout_rate' for p in extra_params: if getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if not hasattr(lowerCamelCase__ , lowerCamelCase__ ) and not hasattr(lowerCamelCase__ , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) continue __lowerCamelCase : List[Any] = p if hasattr(lowerCamelCase__ , lowerCamelCase__ ) else equivalent_param[p] setattr(lowerCamelCase__ , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) return hparams, config
652
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCamelCase = { """configuration_pegasus_x""": ["""PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PegasusXConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ """PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST""", """PegasusXForConditionalGeneration""", """PegasusXModel""", """PegasusXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
341
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a =logging.get_logger(__name__) # General docstring a ="""MobileNetV1Config""" # Base docstring a ="""google/mobilenet_v1_1.0_224""" a =[1, 1024, 7, 7] # Image classification docstring a ="""google/mobilenet_v1_1.0_224""" a ="""tabby, tabby cat""" a =[ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> str: __lowerCamelCase : str = {} if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = model.mobilenet_va else: __lowerCamelCase : List[str] = model __lowerCamelCase : List[Any] = 'MobilenetV1/Conv2d_0/' __lowerCamelCase : List[Any] = backbone.conv_stem.convolution.weight __lowerCamelCase : List[str] = backbone.conv_stem.normalization.bias __lowerCamelCase : Tuple = backbone.conv_stem.normalization.weight __lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean __lowerCamelCase : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(1_3 ): __lowerCamelCase : Any = i + 1 __lowerCamelCase : Union[str, Any] = i * 2 __lowerCamelCase : Optional[Any] = backbone.layer[pt_index] __lowerCamelCase : Optional[int] = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" __lowerCamelCase : Tuple = pointer.convolution.weight __lowerCamelCase : Optional[Any] = pointer.normalization.bias __lowerCamelCase : Union[str, Any] = pointer.normalization.weight __lowerCamelCase : List[str] = pointer.normalization.running_mean __lowerCamelCase : Union[str, Any] = pointer.normalization.running_var __lowerCamelCase : int = backbone.layer[pt_index + 1] __lowerCamelCase : Union[str, Any] = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" __lowerCamelCase : Optional[Any] = pointer.convolution.weight __lowerCamelCase : Any = pointer.normalization.bias __lowerCamelCase : str = pointer.normalization.weight __lowerCamelCase : Dict = pointer.normalization.running_mean __lowerCamelCase : List[str] = pointer.normalization.running_var if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __lowerCamelCase : Any = model.classifier.weight __lowerCamelCase : int = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __lowerCamelCase : List[str] = tf.train.list_variables(lowerCamelCase__ ) __lowerCamelCase : List[str] = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) __lowerCamelCase : Any = tf.train.load_variable(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[Any] = array # Build TF to PyTorch weights loading map __lowerCamelCase : Tuple = _build_tf_to_pytorch_map(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue __lowerCamelCase : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __lowerCamelCase : List[str] = np.transpose(lowerCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __lowerCamelCase : Any = array.squeeze().transpose() else: __lowerCamelCase : Tuple = np.transpose(lowerCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) __lowerCamelCase : Optional[Any] = torch.from_numpy(lowerCamelCase__ ) tf_weights.pop(lowerCamelCase__ , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp' , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp_1' , lowerCamelCase__ ) tf_weights.pop(name + '/ExponentialMovingAverage' , lowerCamelCase__ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: __lowerCamelCase , __lowerCamelCase : int = features.shape[-2:] __lowerCamelCase , __lowerCamelCase : List[str] = conv_layer.stride __lowerCamelCase , __lowerCamelCase : str = conv_layer.kernel_size if in_height % stride_height == 0: __lowerCamelCase : Optional[int] = max(kernel_height - stride_height , 0 ) else: __lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __lowerCamelCase : List[str] = max(kernel_width - stride_width , 0 ) else: __lowerCamelCase : List[str] = max(kernel_width - (in_width % stride_width) , 0 ) __lowerCamelCase : List[str] = pad_along_width // 2 __lowerCamelCase : Optional[int] = pad_along_width - pad_left __lowerCamelCase : Any = pad_along_height // 2 __lowerCamelCase : List[Any] = pad_along_height - pad_top __lowerCamelCase : Union[str, Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(lowerCamelCase__ , lowerCamelCase__ , 'constant' , 0.0 ) class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[bool or str] = True ,): super().__init__() __lowerCamelCase : Dict = config if in_channels % groups != 0: raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups.") if out_channels % groups != 0: raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups.") __lowerCamelCase : Optional[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2) __lowerCamelCase : Optional[int] = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__ ,padding_mode='zeros' ,) if use_normalization: __lowerCamelCase : Optional[int] = nn.BatchNormad( num_features=SCREAMING_SNAKE_CASE__ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=SCREAMING_SNAKE_CASE__ ,track_running_stats=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Dict = None if use_activation: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = ACTaFN[use_activation] elif isinstance(config.hidden_act ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = ACTaFN[config.hidden_act] else: __lowerCamelCase : List[str] = config.hidden_act else: __lowerCamelCase : List[str] = None def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): if self.config.tf_padding: __lowerCamelCase : Any = apply_tf_padding(SCREAMING_SNAKE_CASE__ ,self.convolution) __lowerCamelCase : Optional[int] = self.convolution(SCREAMING_SNAKE_CASE__) if self.normalization is not None: __lowerCamelCase : Dict = self.normalization(SCREAMING_SNAKE_CASE__) if self.activation is not None: __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return features class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = MobileNetVaConfig _UpperCAmelCase : List[str] = load_tf_weights_in_mobilenet_va _UpperCAmelCase : List[str] = '''mobilenet_v1''' _UpperCAmelCase : Any = '''pixel_values''' _UpperCAmelCase : int = False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[nn.Linear, nn.Convad]): if isinstance(SCREAMING_SNAKE_CASE__ ,(nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ ,nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : bool = True): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = config __lowerCamelCase : Optional[int] = 3_2 __lowerCamelCase : List[str] = max(int(depth * config.depth_multiplier) ,config.min_depth) __lowerCamelCase : Optional[Any] = MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=config.num_channels ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=2 ,) __lowerCamelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __lowerCamelCase : str = nn.ModuleList() for i in range(1_3): __lowerCamelCase : str = out_channels if strides[i] == 2 or i == 0: depth *= 2 __lowerCamelCase : str = max(int(depth * config.depth_multiplier) ,config.min_depth) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=strides[i] ,groups=SCREAMING_SNAKE_CASE__ ,)) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,)) __lowerCamelCase : Optional[int] = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') __lowerCamelCase : Optional[Any] = self.conv_stem(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Any = all_hidden_states + (hidden_states,) __lowerCamelCase : Optional[Any] = hidden_states if self.pooler is not None: __lowerCamelCase : Tuple = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__) ,start_dim=1) else: __lowerCamelCase : List[str] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = config.num_labels __lowerCamelCase : Optional[Any] = MobileNetVaModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __lowerCamelCase : Any = nn.Dropout(config.classifier_dropout_prob ,inplace=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Optional[int] = self.mobilenet_va(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] = self.classifier(self.dropout(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : int = 'single_label_classification' else: __lowerCamelCase : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : Tuple = MSELoss() if self.num_labels == 1: __lowerCamelCase : int = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : Union[str, Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : List[str] = CrossEntropyLoss() __lowerCamelCase : List[str] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : int = BCEWithLogitsLoss() __lowerCamelCase : int = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states ,)
652
0
'''simple docstring''' lowercase__ = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowercase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowercase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
638
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = cva.getAffineTransform(lowerCamelCase__ , lowerCamelCase__ ) return cva.warpAffine(lowerCamelCase__ , lowerCamelCase__ , (rows, cols) ) if __name__ == "__main__": # read original image a =cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value a =cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a , a =gray_img.shape # set different points to rotate image a =np.array([[50, 50], [200, 50], [50, 200]], np.floataa) a =np.array([[10, 100], [200, 50], [100, 250]], np.floataa) a =np.array([[50, 50], [150, 50], [120, 200]], np.floataa) a =np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list a =[ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a =plt.figure(1) a =["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
652
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
457
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : List[str] = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCamelCase__ ) if number < 1: __lowerCamelCase : int = F"Input value of [number={number}] must be > 0" raise ValueError(lowerCamelCase__ ) elif number == 1: return 3 elif number == 2: return 5 else: __lowerCamelCase : Any = int(math.log(number // 3 , 2 ) ) + 2 __lowerCamelCase : List[Any] = [3, 5] __lowerCamelCase : Union[str, Any] = 2 __lowerCamelCase : List[str] = 3 for block in range(1 , lowerCamelCase__ ): for _ in range(lowerCamelCase__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): a =0 try: a =proth(number) except ValueError: print(F"""ValueError: there is no {number}th Proth number""") continue print(F"""The {number}th Proth number: {value}""")
652
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github _a : Dict = [ """good first issue""", """good second issue""", """good difficult issue""", """enhancement""", """new pipeline/model""", """new scheduler""", """wip""", ] def _lowerCAmelCase ( ) -> str: __lowerCAmelCase = Github(os.environ["""GITHUB_TOKEN"""] ) __lowerCAmelCase = g.get_repo("""huggingface/diffusers""" ) __lowerCAmelCase = repo.get_issues(state="""open""" ) for issue in open_issues: __lowerCAmelCase = sorted(issue.get_comments() , key=lambda lowercase : i.created_at , reverse=lowerCamelCase__ ) __lowerCAmelCase = 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()
689
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class A_ ( unittest.TestCase ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=7 ,SCREAMING_SNAKE_CASE__ : Any=3 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0 ,SCREAMING_SNAKE_CASE__ : int=4_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[str]=1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : Tuple=True ,): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCamelCase : List[Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} __lowerCamelCase : str = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : int = num_channels __lowerCamelCase : Dict = min_resolution __lowerCamelCase : Tuple = max_resolution __lowerCamelCase : Dict = do_resize __lowerCamelCase : List[Any] = size __lowerCamelCase : Tuple = do_normalize __lowerCamelCase : Any = image_mean __lowerCamelCase : List[str] = image_std __lowerCamelCase : List[Any] = do_rescale __lowerCamelCase : str = rescale_factor __lowerCamelCase : Tuple = do_pad def lowerCAmelCase ( self : Dict): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=False): if not batched: __lowerCamelCase : Optional[Any] = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ ,Image.Image): __lowerCamelCase , __lowerCamelCase : Any = image.size else: __lowerCamelCase , __lowerCamelCase : Any = image.shape[1], image.shape[2] if w < h: __lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w) __lowerCamelCase : Tuple = self.size['shortest_edge'] elif w > h: __lowerCamelCase : Union[str, Any] = self.size['shortest_edge'] __lowerCamelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h) else: __lowerCamelCase : List[Any] = self.size['shortest_edge'] __lowerCamelCase : Optional[int] = self.size['shortest_edge'] else: __lowerCamelCase : List[str] = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase : List[Any] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) __lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[0])[0] __lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[1])[1] return expected_height, expected_width @require_torch @require_vision class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[int] = DetaImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = DetaImageProcessingTester(self) @property def lowerCAmelCase ( self : Any): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_std')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_rescale')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_pad')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'size')) def lowerCAmelCase ( self : str): __lowerCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size ,{'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}) self.assertEqual(image_processor.do_pad ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): pass def lowerCAmelCase ( self : List[str]): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random PIL images __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,Image.Image) # Test not batched input __lowerCamelCase : List[Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : str): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,np.ndarray) # Test not batched input __lowerCamelCase : Tuple = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : int): # Initialize image_processing __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,torch.Tensor) # Test not batched input __lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) @slow def lowerCAmelCase ( self : Optional[Any]): # prepare image and target __lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r') as f: __lowerCamelCase : List[str] = json.loads(f.read()) __lowerCamelCase : Union[str, Any] = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them __lowerCamelCase : Optional[int] = DetaImageProcessor() __lowerCamelCase : int = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Dict = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : int = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : Tuple = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : List[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify orig_size __lowerCamelCase : str = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : int = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__)) @slow def lowerCAmelCase ( self : str): # prepare image, target and masks_path __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r') as f: __lowerCamelCase : Tuple = json.loads(f.read()) __lowerCamelCase : List[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} __lowerCamelCase : Optional[int] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them __lowerCamelCase : List[str] = DetaImageProcessor(format='coco_panoptic') __lowerCamelCase : Optional[Any] = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,masks_path=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : Tuple = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : int = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : int = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify masks __lowerCamelCase : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,SCREAMING_SNAKE_CASE__) # verify orig_size __lowerCamelCase : Any = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : Any = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
652
0
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow UpperCAmelCase__ : Optional[Any] = False class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase__ ( self , UpperCamelCase=32) -> Optional[Any]: set_seed(0) UpperCamelCase__ : Tuple = UNetaDModel(sample_size=SCREAMING_SNAKE_CASE__ , in_channels=3 , out_channels=3) UpperCamelCase__ : str = torch.optim.SGD(model.parameters() , lr=0.0001) return model, optimizer @slow def lowerCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase__ : List[Any] = 'cpu' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable UpperCamelCase__ : Dict = DDPMScheduler( num_train_timesteps=10_00 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='linear' , clip_sample=SCREAMING_SNAKE_CASE__ , ) UpperCamelCase__ : Union[str, Any] = DDIMScheduler( num_train_timesteps=10_00 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='linear' , clip_sample=SCREAMING_SNAKE_CASE__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0) UpperCamelCase__ : Optional[int] = [torch.randn((4, 3, 32, 32)).clip(-1 , 1).to(SCREAMING_SNAKE_CASE__) for _ in range(4)] UpperCamelCase__ : int = [torch.randn((4, 3, 32, 32)).to(SCREAMING_SNAKE_CASE__) for _ in range(4)] UpperCamelCase__ : str = [torch.randint(0 , 10_00 , (4,)).long().to(SCREAMING_SNAKE_CASE__) for _ in range(4)] # train with a DDPM scheduler UpperCamelCase__ : str = self.get_model_optimizer(resolution=32) model.train().to(SCREAMING_SNAKE_CASE__) for i in range(4): optimizer.zero_grad() UpperCamelCase__ : List[str] = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) UpperCamelCase__ : List[str] = model(SCREAMING_SNAKE_CASE__ , timesteps[i]).sample UpperCamelCase__ : List[Any] = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , noise[i]) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM UpperCamelCase__ : List[Any] = self.get_model_optimizer(resolution=32) model.train().to(SCREAMING_SNAKE_CASE__) for i in range(4): optimizer.zero_grad() UpperCamelCase__ : Dict = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) UpperCamelCase__ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , timesteps[i]).sample UpperCamelCase__ : str = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , noise[i]) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5)) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5))
410
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_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[Any] = KandinskyVaaControlnetPipeline _UpperCAmelCase : Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : int = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : List[Any] = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _UpperCAmelCase : Tuple = False @property def lowerCAmelCase ( self : Tuple): return 3_2 @property def lowerCAmelCase ( self : List[Any]): return 3_2 @property def lowerCAmelCase ( self : str): return self.time_input_dim @property def lowerCAmelCase ( self : List[str]): return self.time_input_dim * 4 @property def lowerCAmelCase ( self : List[str]): return 1_0_0 @property def lowerCAmelCase ( self : Dict): torch.manual_seed(0) __lowerCamelCase : 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, } __lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__) return model @property def lowerCAmelCase ( self : Union[str, Any]): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Optional[Any]): torch.manual_seed(0) __lowerCamelCase : int = VQModel(**self.dummy_movq_kwargs) return model def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = self.dummy_unet __lowerCamelCase : List[Any] = self.dummy_movq __lowerCamelCase : str = DDIMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='linear' ,beta_start=0.00085 ,beta_end=0.012 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Dict = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=0): __lowerCamelCase : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1)).to( SCREAMING_SNAKE_CASE__) # create hint __lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) if str(SCREAMING_SNAKE_CASE__).startswith('mps'): __lowerCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 6_4, 'width': 6_4, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = 'cpu' __lowerCamelCase : Tuple = self.get_dummy_components() __lowerCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = output.images __lowerCamelCase : Tuple = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) ,return_dict=SCREAMING_SNAKE_CASE__ ,)[0] __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : List[str] = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]) assert ( np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : int): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy') __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png') __lowerCamelCase : Tuple = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 255.0 __lowerCamelCase : str = hint.permute(2 ,0 ,1).unsqueeze(0) __lowerCamelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa) pipe_prior.to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' ,torch_dtype=torch.floataa) __lowerCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE__) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 'A robot, 4k photo' __lowerCamelCase : List[str] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe_prior( SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple() __lowerCamelCase : Optional[Any] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase : Any = pipeline( image_embeds=SCREAMING_SNAKE_CASE__ ,negative_image_embeds=SCREAMING_SNAKE_CASE__ ,hint=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
652
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCamelCase : """simple docstring""" def A ( self : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Dict): return None class __lowerCamelCase : """simple docstring""" def A ( self : Tuple , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[Any]): return None class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" a = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def A ( self : str): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE__ , 'tf' , 12 , **SCREAMING_SNAKE_CASE__) @require_torch @slow def A ( self : List[str]): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , **SCREAMING_SNAKE_CASE__) @require_torch @slow def A ( self : Optional[int]): from transformers import BertModel _A : Optional[Any] = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t') as vocab_file: vocab_file.write('\n'.join(SCREAMING_SNAKE_CASE__)) vocab_file.flush() _A : Union[str, Any] = BertTokenizerFast(vocab_file.name) with TemporaryDirectory() as bert_save_dir: _A : int = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE__))) model.save_pretrained(SCREAMING_SNAKE_CASE__) self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , SCREAMING_SNAKE_CASE__) @require_tf @slow def A ( self : Dict): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _A : int = self._test_export(SCREAMING_SNAKE_CASE__ , 'tf' , 12 , **SCREAMING_SNAKE_CASE__) _A : List[Any] = quantize(Path(SCREAMING_SNAKE_CASE__)) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE__).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model') @require_torch @slow def A ( self : Tuple): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _A : List[Any] = self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , **SCREAMING_SNAKE_CASE__) _A : int = quantize(SCREAMING_SNAKE_CASE__) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE__).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model') def A ( self : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Any=None , **SCREAMING_SNAKE_CASE : List[Any]): try: # Compute path with TemporaryDirectory() as tempdir: _A : str = Path(SCREAMING_SNAKE_CASE__).joinpath('model.onnx') # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE__) @require_torch @require_tokenizers @slow def A ( self : Dict): from transformers import BertModel _A : List[Any] = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random')) _A : Dict = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random') self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'pt') @require_tf @require_tokenizers @slow def A ( self : List[str]): from transformers import TFBertModel _A : Union[str, Any] = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random')) _A : Optional[int] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random') self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'tf') def A ( self : Optional[int] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Union[str, Any]): _A : Optional[int] = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) _A : List[str] = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] _A : Dict = infer_shapes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE__) , len(SCREAMING_SNAKE_CASE__)) self.assertTrue(all(var_name in shapes for var_name in variable_names)) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE__) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE__) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: 'batch', 1: 'sequence'}) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['output_0'] , {0: 'batch', 1: 'sequence'}) self.assertDictEqual(shapes['output_1'] , {0: 'batch'}) def A ( self : Optional[int]): _A : Dict = ['input_ids', 'attention_mask', 'token_type_ids'] _A : List[str] = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} _A : Dict = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE__) , 3) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE__) , set(SCREAMING_SNAKE_CASE__)) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE__ , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask'])) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) _A : Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE__) , 1) self.assertEqual(len(SCREAMING_SNAKE_CASE__) , 1) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['input_ids']) self.assertEqual(ordered_input_names[0] , 'input_ids') def A ( self : List[Any]): _A : Any = generate_identified_filename(Path('/home/something/my_fake_model.onnx') , '-test') self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix())
128
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : _UpperCAmelCase : int = XGLMConfig _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Tuple = '''gelu''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 ,SCREAMING_SNAKE_CASE__ : Tuple=7 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=9_9 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : Tuple=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,): __lowerCamelCase : List[str] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_input_mask __lowerCamelCase : str = use_labels __lowerCamelCase : Any = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : List[str] = ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : Tuple = activation_dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Any = None __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 2 __lowerCamelCase : Dict = 1 def lowerCAmelCase ( self : Any): return XGLMConfig.from_pretrained('facebook/xglm-564M') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) ,clip_value_min=0 ,clip_value_max=3) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : int = self.get_config() __lowerCamelCase : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[Any]): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=SCREAMING_SNAKE_CASE__ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : int): __lowerCamelCase : int = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : str = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : str = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _UpperCAmelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else () _UpperCAmelCase : str = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Tuple = TFXGLMModelTester(self) __lowerCamelCase : int = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,n_embd=3_7) def lowerCAmelCase ( self : List[Any]): self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : str): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.') def lowerCAmelCase ( self : Union[str, Any]): super().test_resize_token_embeddings() @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True): __lowerCamelCase : Any = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]] ,dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __lowerCamelCase : Optional[Any] = [2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1] # fmt: on __lowerCamelCase : int = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') tf.random.set_seed(0) __lowerCamelCase : Optional[Any] = tokenizer('Today is a nice day and' ,return_tensors='tf') __lowerCamelCase : List[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0'): __lowerCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,seed=[7, 0]) __lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = 'left' # use different length sentences to test batching __lowerCamelCase : List[str] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __lowerCamelCase : List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='tf' ,padding=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['input_ids'] __lowerCamelCase : Dict = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=inputs['attention_mask'] ,max_new_tokens=1_2) __lowerCamelCase : Tuple = tokenizer(sentences[0] ,return_tensors='tf').input_ids __lowerCamelCase : List[str] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : Any = tokenizer(sentences[1] ,return_tensors='tf').input_ids __lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tokenizer.decode(output_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[non_padded_sentence, padded_sentence])
652
0
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase : """simple docstring""" @staticmethod def A__ ( *_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): pass @is_pipeline_test @require_vision class UpperCamelCase ( unittest.TestCase ): """simple docstring""" @require_torch def A__ ( self : str ): A__ = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A__ = image_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) A__ = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], ] , ) @require_tf def A__ ( self : Optional[Any] ): A__ = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A__ = image_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) A__ = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], [ {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, {'''score''': 0.333, '''label''': ANY(SCREAMING_SNAKE_CASE__ )}, ], ] , ) @slow @require_torch def A__ ( self : Optional[Any] ): A__ = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A__ = image_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) A__ = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def A__ ( self : Optional[Any] ): A__ = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) A__ = image_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) A__ = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
571
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
652
0
'''simple docstring''' import math def UpperCamelCase ( _lowerCamelCase : Dict ): A__ = [True] * n A__ = False A__ = False A__ = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): A__ = i * 2 while index < n: A__ = False A__ = index + i A__ = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def UpperCamelCase ( _lowerCamelCase : Tuple = 99_99_66_66_33_33 ): A__ = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_00 A__ = prime_sieve(lowerCamelCase__ ) A__ = 0 A__ = 0 A__ = primes[prime_index] while (last_prime**2) <= limit: A__ = primes[prime_index + 1] A__ = last_prime**2 A__ = next_prime**2 # Get numbers divisible by lps(current) A__ = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A__ = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A__ = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A__ = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
440
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a =logging.get_logger(__name__) # General docstring a ="""RegNetConfig""" # Base docstring a ="""facebook/regnet-y-040""" a =[1, 1088, 7, 7] # Image classification docstring a ="""facebook/regnet-y-040""" a ="""tabby, tabby cat""" a =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : Optional[str] = "relu" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2) __lowerCamelCase : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,strides=SCREAMING_SNAKE_CASE__ ,padding='VALID' ,groups=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution' ,) __lowerCamelCase : int = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') __lowerCamelCase : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Dict): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = config.num_channels __lowerCamelCase : Dict = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='embedder' ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__)[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,strides=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution') __lowerCamelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False): return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__) ,training=SCREAMING_SNAKE_CASE__) class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') __lowerCamelCase : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='relu' ,name='attention.0'), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='sigmoid' ,name='attention.2'), ] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__) for layer_module in self.attention: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = hidden_state * pooled return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[Any]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = max(1 ,out_channels // config.groups_width) __lowerCamelCase : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.2'), ] __lowerCamelCase : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : int = hidden_state for layer_module in self.layers: __lowerCamelCase : List[str] = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : int = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1 __lowerCamelCase : Tuple = max(1 ,out_channels // config.groups_width) __lowerCamelCase : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ ,reduced_channels=int(round(in_channels / 4)) ,name='layer.2'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.3'), ] __lowerCamelCase : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[int] = hidden_state for layer_module in self.layers: __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : Any = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCamelCase : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='layers.0'), *[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,name=F"layers.{i+1}") for i in range(depth - 1)], ] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): for layer_module in self.layers: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='stages.0' ,)) __lowerCamelCase : Optional[int] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:])): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__ ,name=F"stages.{i+1}")) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Optional[Any] = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__) @keras_serializable class A_ ( tf.keras.layers.Layer ): _UpperCAmelCase : List[Any] = RegNetConfig def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = config __lowerCamelCase : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ ,name='embedder') __lowerCamelCase : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ ,name='encoder') __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') @unpack_inputs def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,): __lowerCamelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = encoder_outputs[0] __lowerCamelCase : int = self.pooler(SCREAMING_SNAKE_CASE__) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) __lowerCamelCase : str = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) for h in encoder_outputs[1]]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : Optional[int] = '''regnet''' _UpperCAmelCase : List[Any] = '''pixel_values''' @property def lowerCAmelCase ( self : int): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) ,dtype=tf.floataa)} a =r""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : int=False ,): __lowerCamelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__ ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : str): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = config.num_labels __lowerCamelCase : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') # classification head __lowerCamelCase : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='classifier.1') if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Any=False ,): __lowerCamelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str = self.regnet( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states)
652
0
def snake_case_ (__A : List[Any] = 5_0 ) -> int: __lowerCAmelCase : str = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F'{solution() = }')
651
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels a =object() # For specifying empty leaf dict `{}` a =object() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCamelCase__ ) - len(lowerCamelCase__ ) + 1 ): __lowerCamelCase : str = [x.match(lowerCamelCase__ ) for x, y in zip(lowerCamelCase__ , ks[i:] )] if matches and all(lowerCamelCase__ ): return True return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: def replace(lowerCamelCase__ , lowerCamelCase__ ): for rule, replacement in rules: if _match(lowerCamelCase__ , lowerCamelCase__ ): return replacement return val return replace def SCREAMING_SNAKE_CASE__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , lowerCamelCase__ )), (("transformer", "wte", "embedding"), P('mp' , lowerCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase__ , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCamelCase__ , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = _get_partition_rules() __lowerCamelCase : Optional[Any] = _replacement_rules(lowerCamelCase__ ) __lowerCamelCase : Tuple = {k: _unmatched for k in flatten_dict(lowerCamelCase__ )} __lowerCamelCase : List[Any] = {k: replace(lowerCamelCase__ , lowerCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCamelCase__ ) )
652
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets A = '''\ @inproceedings{snover-etal-2006-study, title = \"A Study of Translation Edit Rate with Targeted Human Annotation\", author = \"Snover, Matthew and Dorr, Bonnie and Schwartz, Rich and Micciulla, Linnea and Makhoul, John\", booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\", month = aug # \" 8-12\", year = \"2006\", address = \"Cambridge, Massachusetts, USA\", publisher = \"Association for Machine Translation in the Americas\", url = \"https://aclanthology.org/2006.amta-papers.25\", pages = \"223--231\", } @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } ''' A = '''\ TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu (https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found here: https://github.com/jhclark/tercom. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information. ''' A = ''' Produces TER scores alongside the number of edits and reference length. Args: predictions (list of str): The system stream (a sequence of segments). references (list of list of str): A list of one or more reference streams (each a sequence of segments). normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters, as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana. Only applies if `normalized = True`. Defaults to `False`. case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`. Returns: \'score\' (float): TER score (num_edits / sum_ref_lengths * 100) \'num_edits\' (int): The cumulative number of edits \'ref_length\' (float): The cumulative average reference length Examples: Example 1: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0} Example 2: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0} Example 3: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... normalized=True, ... case_sensitive=True) >>> print(results) {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5} Example 4: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0} Example 5: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _lowerCamelCase ( self : List[str] ) -> Any: if version.parse(scb.__version__ ) < version.parse('1.4.12' ): raise ImportWarning( 'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n' 'You can install it with `pip install "sacrebleu>=1.4.12"`.' ) return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='http://www.cs.umd.edu/~snover/tercom/' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Sequence(datasets.Value('string' ,id='sequence' ) ,id='references' ), } ) ,codebase_urls=['https://github.com/mjpost/sacreBLEU#ter'] ,reference_urls=[ 'https://github.com/jhclark/tercom', ] ,) def _lowerCamelCase ( self : int ,UpperCamelCase : List[str] ,UpperCamelCase : Union[str, Any] ,UpperCamelCase : bool = False ,UpperCamelCase : bool = False ,UpperCamelCase : bool = False ,UpperCamelCase : bool = False ,) -> Optional[Any]: _lowercase : Dict = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) _lowercase : int = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] _lowercase : Dict = TER( normalized=SCREAMING_SNAKE_CASE__ ,no_punct=SCREAMING_SNAKE_CASE__ ,asian_support=SCREAMING_SNAKE_CASE__ ,case_sensitive=SCREAMING_SNAKE_CASE__ ,) _lowercase : Dict = sb_ter.corpus_score(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
125
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list: __lowerCamelCase : Union[str, Any] = [True] * n __lowerCamelCase : List[Any] = False __lowerCamelCase : int = False __lowerCamelCase : Any = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __lowerCamelCase : List[str] = i * 2 while index < n: __lowerCamelCase : Optional[int] = False __lowerCamelCase : List[Any] = index + i __lowerCamelCase : Optional[Any] = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 9_9_9_9_6_6_6_6_3_3_3_3 ) -> int: __lowerCamelCase : Optional[Any] = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_0_0 __lowerCamelCase : Dict = prime_sieve(lowerCamelCase__ ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Any = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase : Any = primes[prime_index + 1] __lowerCamelCase : Optional[Any] = last_prime**2 __lowerCamelCase : Dict = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase : Tuple = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase : List[Any] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
652
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def __init__( self :List[Any], snake_case :Any, snake_case :str=7, snake_case :Any=3, snake_case :Optional[Any]=30, snake_case :int=400, snake_case :Optional[Any]=True, snake_case :Optional[int]=None, snake_case :Any=True, snake_case :Union[str, Any]=[0.5, 0.5, 0.5], snake_case :Dict=[0.5, 0.5, 0.5], snake_case :List[str]=True, snake_case :List[str]=1 / 255, snake_case :Tuple=True, ): """simple docstring""" _lowercase =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _lowercase =parent _lowercase =batch_size _lowercase =num_channels _lowercase =min_resolution _lowercase =max_resolution _lowercase =do_resize _lowercase =size _lowercase =do_normalize _lowercase =image_mean _lowercase =image_std _lowercase =do_rescale _lowercase =rescale_factor _lowercase =do_pad def UpperCamelCase__ ( self :Dict): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCamelCase__ ( self :Any, snake_case :str, snake_case :List[str]=False): """simple docstring""" if not batched: _lowercase =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__, Image.Image): _lowercase =image.size else: _lowercase =image.shape[1], image.shape[2] if w < h: _lowercase =int(self.size['shortest_edge'] * h / w) _lowercase =self.size['shortest_edge'] elif w > h: _lowercase =self.size['shortest_edge'] _lowercase =int(self.size['shortest_edge'] * w / h) else: _lowercase =self.size['shortest_edge'] _lowercase =self.size['shortest_edge'] else: _lowercase =[] for image in image_inputs: _lowercase =self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) _lowercase =max(SCREAMING_SNAKE_CASE__, key=lambda snake_case: item[0])[0] _lowercase =max(SCREAMING_SNAKE_CASE__, key=lambda snake_case: item[1])[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( _a , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Optional[int] =DetaImageProcessor if is_vision_available() else None def UpperCamelCase__ ( self :Optional[Any]): """simple docstring""" _lowercase =DetaImageProcessingTester(self) @property def UpperCamelCase__ ( self :Any): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self :Dict): """simple docstring""" _lowercase =self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'image_std')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'do_rescale')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'do_pad')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__, 'size')) def UpperCamelCase__ ( self :str): """simple docstring""" _lowercase =self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {'shortest_edge': 18, 'longest_edge': 1333}) self.assertEqual(image_processor.do_pad, SCREAMING_SNAKE_CASE__) def UpperCamelCase__ ( self :Any): """simple docstring""" pass def UpperCamelCase__ ( self :List[str]): """simple docstring""" _lowercase =self.image_processing_class(**self.image_processor_dict) # create random PIL images _lowercase =prepare_image_inputs(self.image_processor_tester, equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__, Image.Image) # Test not batched input _lowercase =image_processing(image_inputs[0], return_tensors='pt').pixel_values _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__) _lowercase =image_processing(SCREAMING_SNAKE_CASE__, return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) def UpperCamelCase__ ( self :str): """simple docstring""" _lowercase =self.image_processing_class(**self.image_processor_dict) # create random numpy tensors _lowercase =prepare_image_inputs(self.image_processor_tester, equal_resolution=SCREAMING_SNAKE_CASE__, numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__, np.ndarray) # Test not batched input _lowercase =image_processing(image_inputs[0], return_tensors='pt').pixel_values _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowercase =image_processing(SCREAMING_SNAKE_CASE__, return_tensors='pt').pixel_values _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) def UpperCamelCase__ ( self :int): """simple docstring""" _lowercase =self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors _lowercase =prepare_image_inputs(self.image_processor_tester, equal_resolution=SCREAMING_SNAKE_CASE__, torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__, torch.Tensor) # Test not batched input _lowercase =image_processing(image_inputs[0], return_tensors='pt').pixel_values _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape, (1, self.image_processor_tester.num_channels, expected_height, expected_width), ) # Test batched _lowercase =image_processing(SCREAMING_SNAKE_CASE__, return_tensors='pt').pixel_values _lowercase =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) @slow def UpperCamelCase__ ( self :Optional[Any]): """simple docstring""" _lowercase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt', 'r') as f: _lowercase =json.loads(f.read()) _lowercase ={'image_id': 3_9769, 'annotations': target} # encode them _lowercase =DetaImageProcessor() _lowercase =image_processing(images=SCREAMING_SNAKE_CASE__, annotations=SCREAMING_SNAKE_CASE__, return_tensors='pt') # verify pixel values _lowercase =torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape, SCREAMING_SNAKE_CASE__) _lowercase =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3], SCREAMING_SNAKE_CASE__, atol=1e-4)) # verify area _lowercase =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'], SCREAMING_SNAKE_CASE__)) # verify boxes _lowercase =torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape, SCREAMING_SNAKE_CASE__) _lowercase =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0], SCREAMING_SNAKE_CASE__, atol=1e-3)) # verify image_id _lowercase =torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'], SCREAMING_SNAKE_CASE__)) # verify is_crowd _lowercase =torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'], SCREAMING_SNAKE_CASE__)) # verify class_labels _lowercase =torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'], SCREAMING_SNAKE_CASE__)) # verify orig_size _lowercase =torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'], SCREAMING_SNAKE_CASE__)) # verify size _lowercase =torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'], SCREAMING_SNAKE_CASE__)) @slow def UpperCamelCase__ ( self :str): """simple docstring""" _lowercase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt', 'r') as f: _lowercase =json.loads(f.read()) _lowercase ={'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target} _lowercase =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them _lowercase =DetaImageProcessor(format='coco_panoptic') _lowercase =image_processing(images=SCREAMING_SNAKE_CASE__, annotations=SCREAMING_SNAKE_CASE__, masks_path=SCREAMING_SNAKE_CASE__, return_tensors='pt') # verify pixel values _lowercase =torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape, SCREAMING_SNAKE_CASE__) _lowercase =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3], SCREAMING_SNAKE_CASE__, atol=1e-4)) # verify area _lowercase =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'], SCREAMING_SNAKE_CASE__)) # verify boxes _lowercase =torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape, SCREAMING_SNAKE_CASE__) _lowercase =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0], SCREAMING_SNAKE_CASE__, atol=1e-3)) # verify image_id _lowercase =torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'], SCREAMING_SNAKE_CASE__)) # verify is_crowd _lowercase =torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'], SCREAMING_SNAKE_CASE__)) # verify class_labels _lowercase =torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'], SCREAMING_SNAKE_CASE__)) # verify masks _lowercase =82_2873 self.assertEqual(encoding['labels'][0]['masks'].sum().item(), SCREAMING_SNAKE_CASE__) # verify orig_size _lowercase =torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'], SCREAMING_SNAKE_CASE__)) # verify size _lowercase =torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'], SCREAMING_SNAKE_CASE__))
181
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = 1 @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.15 ,SCREAMING_SNAKE_CASE__ : float = 0.01 ,SCREAMING_SNAKE_CASE__ : float = 1348.0 ,SCREAMING_SNAKE_CASE__ : float = 1E-5 ,SCREAMING_SNAKE_CASE__ : int = 1 ,): # standard deviation of the initial noise distribution __lowerCamelCase : int = sigma_max # setable values __lowerCamelCase : List[str] = None self.set_sigmas(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps __lowerCamelCase : Optional[int] = torch.linspace(1 ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,device=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None): __lowerCamelCase : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __lowerCamelCase : Optional[int] = sigma_max if sigma_max is not None else self.config.sigma_max __lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __lowerCamelCase : Optional[Any] = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__) ,math.log(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str]): return torch.where( timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') __lowerCamelCase : List[str] = timestep * torch.ones( sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) __lowerCamelCase : str = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __lowerCamelCase : Dict = timesteps.to(self.discrete_sigmas.device) __lowerCamelCase : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device) __lowerCamelCase : Optional[Any] = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).to(sample.device) __lowerCamelCase : int = torch.zeros_like(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __lowerCamelCase : int = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): __lowerCamelCase : List[Any] = diffusion.unsqueeze(-1) __lowerCamelCase : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __lowerCamelCase : int = randn_tensor( sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__ ,device=sample.device ,dtype=sample.dtype) __lowerCamelCase : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __lowerCamelCase : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,prev_sample_mean=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __lowerCamelCase : Optional[int] = randn_tensor(sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__).to(sample.device) # compute step size from the model_output, the noise, and the snr __lowerCamelCase : str = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __lowerCamelCase : Optional[int] = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): __lowerCamelCase : List[str] = step_size.unsqueeze(-1) __lowerCamelCase : str = sample + step_size * model_output __lowerCamelCase : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,): # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase : int = timesteps.to(original_samples.device) __lowerCamelCase : Any = self.discrete_sigmas.to(original_samples.device)[timesteps] __lowerCamelCase : Optional[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__) * sigmas[:, None, None, None] ) __lowerCamelCase : str = noise + original_samples return noisy_samples def __len__( self : Optional[int]): return self.config.num_train_timesteps
652
0
"""simple docstring""" def _a ( _snake_case , _snake_case ): """simple docstring""" if not len(lowerCamelCase__ ) == len(lowerCamelCase__ ) == 3: raise ValueError("""Please enter a valid equation.""" ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("""Both a & b of two equations can\'t be zero.""" ) # Extract the coefficients UpperCAmelCase = equationa UpperCAmelCase = equationa # Calculate the determinants of the matrices UpperCAmelCase = aa * ba - aa * ba UpperCAmelCase = ca * ba - ca * ba UpperCAmelCase = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("""Infinite solutions. (Consistent system)""" ) else: raise ValueError("""No solution. (Inconsistent system)""" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: UpperCAmelCase = determinant_x / determinant UpperCAmelCase = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
341
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 lowercase__ = get_tests_dir("fixtures") class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : List[Any] ) -> str: """simple docstring""" snake_case : Tuple = mock.Mock() snake_case : str = 500 snake_case : str = {} snake_case : List[Any] = HTTPError snake_case : Optional[Any] = {} # Download this model to make sure it's in the cache. snake_case : str = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE__ ) as mock_head: snake_case : str = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # This check we did call the fake head request mock_head.assert_called() def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" snake_case : Optional[int] = ViTImageProcessor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json''' ) def lowerCAmelCase ( self : int ) -> int: """simple docstring""" with self.assertRaises(SCREAMING_SNAKE_CASE__ ): # config is in subfolder, the following should not work without specifying the subfolder snake_case : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants''' ) snake_case : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/stable-diffusion-all-variants''' , subfolder='''feature_extractor''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @is_staging_test class snake_case__ ( unittest.TestCase ): """simple docstring""" @classmethod def lowerCAmelCase ( cls : Dict ) -> Optional[Any]: """simple docstring""" snake_case : List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @classmethod def lowerCAmelCase ( cls : Tuple ) -> List[str]: """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-image-processor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-image-processor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-image-processor''' ) except HTTPError: pass def lowerCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" snake_case : int = ViTImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ ) image_processor.push_to_hub('''test-image-processor''' , use_auth_token=self._token ) snake_case : List[str] = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='''test-image-processor''' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) snake_case : Tuple = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" snake_case : Optional[int] = ViTImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ ) image_processor.push_to_hub('''valid_org/test-image-processor''' , use_auth_token=self._token ) snake_case : Union[str, Any] = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='''valid_org/test-image-processor-org''' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) snake_case : List[str] = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def lowerCAmelCase ( self : Tuple ) -> List[Any]: """simple docstring""" CustomImageProcessor.register_for_auto_class() snake_case : Optional[Any] = CustomImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ ) image_processor.push_to_hub('''test-dynamic-image-processor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''} , ) snake_case : Union[str, Any] = AutoImageProcessor.from_pretrained( f'{USER}/test-dynamic-image-processor' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , '''CustomImageProcessor''' )
638
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : Optional[int] = [file for file in files if n_ not in file] else: __lowerCamelCase : Dict = [file for file in files if n_identifier not in file] __lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : Optional[int] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : int = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = 'modeling' __lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = Path('src/transformers') __lowerCamelCase : Optional[int] = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : str = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = Path('docs/source') __lowerCamelCase : str = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
652
0
import copy import random from transformers import CLIPTokenizer class __lowercase ( a_ ): """simple docstring""" def __init__( self , *A , **A ) -> str: '''simple docstring''' super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCamelCase = {} def __A ( self , A , *A , **A ) -> Optional[int]: '''simple docstring''' lowerCamelCase = super().add_tokens(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if num_added_tokens == 0: raise ValueError( F'The tokenizer already contains the token {placeholder_token}. Please pass a different' """ `placeholder_token` that is not already in the tokenizer.""" ) def __A ( self , A , *A , A=1 , **A ) -> str: '''simple docstring''' lowerCamelCase = [] if num_vec_per_token == 1: self.try_adding_tokens(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) output.append(SCREAMING_SNAKE_CASE__ ) else: lowerCamelCase = [] for i in range(SCREAMING_SNAKE_CASE__ ): lowerCamelCase = placeholder_token + F'_{i}' self.try_adding_tokens(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) output.append(SCREAMING_SNAKE_CASE__ ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'The tokenizer already has placeholder token {token} that can get confused with' F' {placeholder_token}keep placeholder tokens independent' ) lowerCamelCase = output def __A ( self , A , A=False , A=1.0 ) -> Any: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCamelCase = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=SCREAMING_SNAKE_CASE__ ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: lowerCamelCase = self.token_map[placeholder_token] lowerCamelCase = tokens[: 1 + int(len(SCREAMING_SNAKE_CASE__ ) * prop_tokens_to_load )] if vector_shuffle: lowerCamelCase = copy.copy(SCREAMING_SNAKE_CASE__ ) random.shuffle(SCREAMING_SNAKE_CASE__ ) lowerCamelCase = text.replace(SCREAMING_SNAKE_CASE__ , """ """.join(SCREAMING_SNAKE_CASE__ ) ) return text def __call__( self , A , *A , A=False , A=1.0 , **A ) -> List[Any]: '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( SCREAMING_SNAKE_CASE__ , vector_shuffle=SCREAMING_SNAKE_CASE__ , prop_tokens_to_load=SCREAMING_SNAKE_CASE__ ) , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self , A , *A , A=False , A=1.0 , **A ) -> Union[str, Any]: '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( SCREAMING_SNAKE_CASE__ , vector_shuffle=SCREAMING_SNAKE_CASE__ , prop_tokens_to_load=SCREAMING_SNAKE_CASE__ ) , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
457
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} a ={ """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } a ={"""vinai/bartpho-syllable""": 1024} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Any="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="<s>" ,SCREAMING_SNAKE_CASE__ : int="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<mask>" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = vocab_file __lowerCamelCase : Tuple = monolingual_vocab_file __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__)) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Any = cnt cnt += 1 with open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for line in f.readlines(): __lowerCamelCase : Any = line.strip().split()[0] __lowerCamelCase : List[str] = len(self.fairseq_tokens_to_ids) if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Dict = len(self.fairseq_tokens_to_ids) __lowerCamelCase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): __lowerCamelCase : Tuple = self.__dict__.copy() __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : str = {} __lowerCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Tuple = [self.cls_token_id] __lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Dict = [self.sep_token_id] __lowerCamelCase : 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 lowerCAmelCase ( self : List[str]): return len(self.fairseq_ids_to_tokens) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): return self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Any = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( SCREAMING_SNAKE_CASE__) and os.path.isfile(self.monolingual_vocab_file): copyfile(self.monolingual_vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.monolingual_vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(SCREAMING_SNAKE_CASE__)} \n") return out_vocab_file, out_monolingual_vocab_file
652
0
'''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 PreTrainedTokenizer from ...utils import logging _a : Tuple = logging.get_logger(__name__) _a : Any = """▁""" _a : Tuple = { """vocab_file""": """vocab.json""", """spm_file""": """sentencepiece.bpe.model""", } _a : str = { """vocab_file""": { """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json""" ), }, """spm_file""": { """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model""" ) }, } _a : str = { """facebook/s2t-small-librispeech-asr""": 1_0_2_4, } _a : List[str] = ["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""] _a : List[str] = {"""mustc""": MUSTC_LANGS} class _UpperCAmelCase ( lowerCAmelCase_ ): a : List[str] =VOCAB_FILES_NAMES a : Dict =PRETRAINED_VOCAB_FILES_MAP a : Any =MAX_MODEL_INPUT_SIZES a : Optional[Any] =['''input_ids''', '''attention_mask'''] a : List[int] =[] def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE="<s>",__SCREAMING_SNAKE_CASE="</s>",__SCREAMING_SNAKE_CASE="<pad>",__SCREAMING_SNAKE_CASE="<unk>",__SCREAMING_SNAKE_CASE=False,__SCREAMING_SNAKE_CASE=False,__SCREAMING_SNAKE_CASE=None,__SCREAMING_SNAKE_CASE=None,__SCREAMING_SNAKE_CASE = None,**__SCREAMING_SNAKE_CASE,): '''simple docstring''' __lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__,eos_token=SCREAMING_SNAKE_CASE__,unk_token=SCREAMING_SNAKE_CASE__,pad_token=SCREAMING_SNAKE_CASE__,do_upper_case=SCREAMING_SNAKE_CASE__,do_lower_case=SCREAMING_SNAKE_CASE__,tgt_lang=SCREAMING_SNAKE_CASE__,lang_codes=SCREAMING_SNAKE_CASE__,sp_model_kwargs=self.sp_model_kwargs,**SCREAMING_SNAKE_CASE__,) __lowerCAmelCase = do_upper_case __lowerCAmelCase = do_lower_case __lowerCAmelCase = load_json(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = {v: k for k, v in self.encoder.items()} __lowerCAmelCase = spm_file __lowerCAmelCase = load_spm(SCREAMING_SNAKE_CASE__,self.sp_model_kwargs ) if lang_codes is not None: __lowerCAmelCase = lang_codes __lowerCAmelCase = LANGUAGES[lang_codes] __lowerCAmelCase = [f'<lang:{lang}>' for lang in self.langs] __lowerCAmelCase = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} __lowerCAmelCase = self.lang_tokens __lowerCAmelCase = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: __lowerCAmelCase = {} @property def lowerCamelCase__ ( self ): '''simple docstring''' return len(self.encoder ) @property def lowerCamelCase__ ( self ): '''simple docstring''' return self._tgt_lang @tgt_lang.setter def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = new_tgt_lang self.set_tgt_lang_special_tokens(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = self.lang_code_to_id[tgt_lang] __lowerCAmelCase = [lang_code_id] def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__,out_type=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE__,self.encoder[self.unk_token] ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE__,self.unk_token ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: __lowerCAmelCase = self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " __lowerCAmelCase = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__,token_ids_a=SCREAMING_SNAKE_CASE__,already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = [1] * len(self.prefix_tokens ) __lowerCAmelCase = [1] if token_ids_a is None: return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE__ )) + suffix_ones return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE__ )) + ([0] * len(SCREAMING_SNAKE_CASE__ )) + suffix_ones def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): '''simple docstring''' __lowerCAmelCase = self.__dict__.copy() __lowerCAmelCase = None return state def __setstate__( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = d # for backward compatibility if not hasattr(self,"""sp_model_kwargs""" ): __lowerCAmelCase = {} __lowerCAmelCase = load_spm(self.spm_file,self.sp_model_kwargs ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = None ): '''simple docstring''' __lowerCAmelCase = Path(SCREAMING_SNAKE_CASE__ ) assert save_dir.is_dir(), f'{save_directory} should be a directory' __lowerCAmelCase = save_dir / ( (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file'] ) __lowerCAmelCase = save_dir / ( (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file'] ) save_json(self.encoder,SCREAMING_SNAKE_CASE__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file,SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.spm_file ): with open(SCREAMING_SNAKE_CASE__,"""wb""" ) as fi: __lowerCAmelCase = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (str(SCREAMING_SNAKE_CASE__ ), str(SCREAMING_SNAKE_CASE__ )) def _lowerCAmelCase ( lowercase , lowercase ) -> sentencepiece.SentencePieceProcessor: __lowerCAmelCase = sentencepiece.SentencePieceProcessor(**lowerCamelCase__ ) spm.Load(str(lowerCamelCase__ ) ) return spm def _lowerCAmelCase ( lowercase ) -> Union[Dict, List]: with open(lowerCamelCase__ , """r""" ) as f: return json.load(lowerCamelCase__ ) def _lowerCAmelCase ( lowercase , lowercase ) -> None: with open(lowerCamelCase__ , """w""" ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=2 )
689
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_3 ,SCREAMING_SNAKE_CASE__ : int=3_0 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=3_2 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2 ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Dict = image_size __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = is_training __lowerCamelCase : List[Any] = use_labels __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : List[str] = scope __lowerCamelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCamelCase : str = (image_size // patch_size) ** 2 __lowerCamelCase : str = num_patches + 2 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : List[Any] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any]): return DeiTConfig( 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=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Optional[Any] = TFDeiTModel(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCamelCase : int = 1 __lowerCamelCase : Tuple = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.type_sequence_label_size __lowerCamelCase : List[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = config_and_inputs __lowerCamelCase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _UpperCAmelCase : List[Any] = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = TFDeiTModelTester(self) __lowerCamelCase : Optional[int] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : str): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,tf.keras.layers.Dense)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Any = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=False): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224') __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : Tuple = prepare_img() __lowerCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='tf') # forward pass __lowerCamelCase : int = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tf.constant([-1.0266, 0.1912, -1.2861]) self.assertTrue(np.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
652
0
import math def _lowercase ( __SCREAMING_SNAKE_CASE ) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): UpperCamelCase__ : List[str] = F"""Input value of [number={number}] must be an integer""" raise TypeError(lowerCamelCase__ ) if number < 1: UpperCamelCase__ : int = F"""Input value of [number={number}] must be > 0""" raise ValueError(lowerCamelCase__ ) elif number == 1: return 3 elif number == 2: return 5 else: UpperCamelCase__ : Any = int(math.log(number // 3 , 2 ) ) + 2 UpperCamelCase__ : List[Any] = [3, 5] UpperCamelCase__ : Union[str, Any] = 2 UpperCamelCase__ : List[str] = 3 for block in range(1 , lowerCamelCase__ ): for _ in range(lowerCamelCase__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): UpperCAmelCase__ : int = 0 try: UpperCAmelCase__ : List[str] = proth(number) except ValueError: print(f'''ValueError: there is no {number}th Proth number''') continue print(f'''The {number}th Proth number: {value}''')
410
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] _UpperCAmelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
652
0
'''simple docstring''' from __future__ import annotations import numpy as np def lowerCAmelCase__ ( lowerCamelCase : str ): _A : Union[str, Any] = np.shape(lowerCamelCase__ ) if rows != columns: _A : Union[str, Any] = ( '\'table\' has to be of square shaped array but got a ' F'{rows}x{columns} array:\n{table}' ) raise ValueError(lowerCamelCase__ ) _A : Optional[int] = np.zeros((rows, columns) ) _A : List[str] = np.zeros((rows, columns) ) for i in range(lowerCamelCase__ ): for j in range(lowerCamelCase__ ): _A : Optional[int] = sum(lower[i][k] * upper[k][j] for k in range(lowerCamelCase__ ) ) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists' ) _A : Optional[Any] = (table[i][j] - total) / upper[j][j] _A : Union[str, Any] = 1 for j in range(lowerCamelCase__ ,lowerCamelCase__ ): _A : Any = sum(lower[i][k] * upper[k][j] for k in range(lowerCamelCase__ ) ) _A : Any = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
128
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
652
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __snake_case : Any = logging.get_logger(__name__) __snake_case : Optional[Any] = { '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_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', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def a_ ( __a , __a , __a , __a , __a ): for attribute in key.split('''.''' ): A__ = getattr(lowerCamelCase__ , lowerCamelCase__ ) if weight_type is not None: A__ = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape else: A__ = 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": A__ = value elif weight_type == "weight_g": A__ = value elif weight_type == "weight_v": A__ = value elif weight_type == "bias": A__ = value else: A__ = value logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def a_ ( __a , __a , __a ): A__ = [] A__ = fairseq_model.state_dict() A__ = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): A__ = False if "conv_layers" in name: load_conv_layer( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , hf_model.config.feat_extract_norm == '''group''' , ) A__ = True else: for key, mapped_key in MAPPING.items(): A__ = 'hubert.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') else mapped_key if key in name or (key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0] and not is_finetuned): A__ = True if "*" in mapped_key: A__ = name.split(lowerCamelCase__ )[0].split('''.''' )[-2] A__ = mapped_key.replace('''*''' , lowerCamelCase__ ) if "weight_g" in name: A__ = 'weight_g' elif "weight_v" in name: A__ = 'weight_v' elif "weight" in name: A__ = 'weight' elif "bias" in name: A__ = 'bias' else: A__ = 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 a_ ( __a , __a , __a , __a , __a ): A__ = full_name.split('''conv_layers.''' )[-1] A__ = name.split('''.''' ) A__ = int(items[0] ) A__ = int(items[1] ) if type_id == 0: if "bias" in name: 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.''' ) A__ = 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.''' ) A__ = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: 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." ) A__ = 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.''' ) A__ = 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 a_ ( __a , __a , __a=None , __a=None , __a=True ): if config_path is not None: A__ = HubertConfig.from_pretrained(lowerCamelCase__ ) else: A__ = HubertConfig() if is_finetuned: if dict_path: A__ = Dictionary.load(lowerCamelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq A__ = target_dict.pad_index A__ = target_dict.bos_index A__ = target_dict.eos_index A__ = len(target_dict.symbols ) A__ = os.path.join(lowerCamelCase__ , '''vocab.json''' ) if not os.path.isdir(lowerCamelCase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowerCamelCase__ ) ) return os.makedirs(lowerCamelCase__ , exist_ok=lowerCamelCase__ ) with open(lowerCamelCase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices , lowerCamelCase__ ) A__ = WavaVecaCTCTokenizer( lowerCamelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=lowerCamelCase__ , ) A__ = True if config.feat_extract_norm == 'layer' else False A__ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , ) A__ = WavaVecaProcessor(feature_extractor=lowerCamelCase__ , tokenizer=lowerCamelCase__ ) processor.save_pretrained(lowerCamelCase__ ) A__ = HubertForCTC(lowerCamelCase__ ) else: A__ = HubertModel(lowerCamelCase__ ) if is_finetuned: A__ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: A__ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) A__ = model[0].eval() recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) hf_wavavec.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": __snake_case : Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) __snake_case : int = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
571
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """vocab.txt"""} a ={ """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } a ={ """openbmb/cpm-ant-10b""": 1024, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: __lowerCamelCase : int = collections.OrderedDict() with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as reader: __lowerCamelCase : Optional[int] = reader.readlines() for index, token in enumerate(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = token.rstrip('\n' ) __lowerCamelCase : Union[str, Any] = index return vocab class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[int]="<unk>" ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_0): __lowerCamelCase : str = vocab __lowerCamelCase : Dict = unk_token __lowerCamelCase : int = max_input_chars_per_word def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > self.max_input_chars_per_word: return [self.unk_token] __lowerCamelCase : Tuple = 0 __lowerCamelCase : str = [] while start < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = None while start < end: __lowerCamelCase : Any = ''.join(chars[start:end]) if substr in self.vocab: __lowerCamelCase : Optional[Any] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = end return sub_tokens class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = ['''input_ids''', '''attention_mask'''] _UpperCAmelCase : Optional[int] = False def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple="<d>" ,SCREAMING_SNAKE_CASE__ : Tuple="</d>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="</s>" ,SCREAMING_SNAKE_CASE__ : str="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<unk>" ,SCREAMING_SNAKE_CASE__ : List[Any]="</n>" ,SCREAMING_SNAKE_CASE__ : int="</_>" ,SCREAMING_SNAKE_CASE__ : List[Any]="left" ,**SCREAMING_SNAKE_CASE__ : List[str] ,): requires_backends(self ,['jieba']) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ ,eod_token=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,line_token=SCREAMING_SNAKE_CASE__ ,space_token=SCREAMING_SNAKE_CASE__ ,padding_side=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Optional[Any] = bod_token __lowerCamelCase : Dict = eod_token __lowerCamelCase : Any = load_vocab(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.encoder[space_token] __lowerCamelCase : Dict = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __lowerCamelCase : Optional[Any] = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) __lowerCamelCase : int = {v: k for k, v in self.encoder.items()} __lowerCamelCase : Union[str, Any] = WordpieceTokenizer(vocab=self.encoder ,unk_token=self.unk_token) @property def lowerCAmelCase ( self : List[Any]): return self.encoder[self.bod_token] @property def lowerCAmelCase ( self : Tuple): return self.encoder[self.eod_token] @property def lowerCAmelCase ( self : Union[str, Any]): return self.encoder["\n"] @property def lowerCAmelCase ( self : str): return len(self.encoder) def lowerCAmelCase ( self : str): return dict(self.encoder ,**self.added_tokens_encoder) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Any = [] for x in jieba.cut(SCREAMING_SNAKE_CASE__ ,cut_all=SCREAMING_SNAKE_CASE__): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__)) return output_tokens def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Tuple = [i for i in token_ids if i >= 0] __lowerCamelCase : str = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[Any]): return token in self.encoder def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.encoder.get(SCREAMING_SNAKE_CASE__ ,self.encoder.get(self.unk_token)) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.decoder.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : int = (filename_prefix + '-' if filename_prefix else '') + save_directory __lowerCamelCase : Any = 0 if " " in self.encoder: __lowerCamelCase : Any = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: __lowerCamelCase : str = self.encoder['\n'] del self.encoder["\n"] __lowerCamelCase : str = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Any = token_index writer.write(token + '\n') index += 1 return (vocab_file,) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : List[int] = None): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__))
652
0
'''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 UpperCAmelCase ( unittest.TestCase ): def UpperCAmelCase_ ( self :Tuple )-> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase_ ( self :List[str] )-> int: A__ = 1 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) return image @property def UpperCAmelCase_ ( self :Any )-> Dict: torch.manual_seed(0 ) A__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCAmelCase_ ( self :Optional[Any] )-> List[str]: torch.manual_seed(0 ) A__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCAmelCase_ ( self :Optional[Any] )-> Any: torch.manual_seed(0 ) A__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE__ ) @property def UpperCAmelCase_ ( self :Tuple )-> List[Any]: def extract(*lowercase_ :List[Any] , **lowercase_ :Dict ): class UpperCAmelCase : def __init__( self :Optional[int] )-> Any: A__ = torch.ones([0] ) def UpperCAmelCase_ ( self :Union[str, Any] , lowercase_ :Any )-> Optional[Any]: self.pixel_values.to(SCREAMING_SNAKE_CASE__ ) return self return Out() return extract def UpperCAmelCase_ ( self :Optional[Any] )-> List[str]: A__ = 'cpu' # ensure determinism for the device-dependent torch.Generator A__ = self.dummy_cond_unet A__ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk A__ = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=self.dummy_extractor , ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = 'A painting of a squirrel eating a burger' A__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) A__ = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) A__ = output.images A__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=SCREAMING_SNAKE_CASE__ , )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A__ = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) 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 UpperCAmelCase_ ( self :Tuple )-> Optional[int]: A__ = 'cpu' # ensure determinism for the device-dependent torch.Generator A__ = self.dummy_cond_unet A__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__ ) A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk A__ = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=self.dummy_extractor , ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = 'A painting of a squirrel eating a burger' A__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) A__ = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) A__ = output.images A__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=SCREAMING_SNAKE_CASE__ , )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A__ = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) 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 UpperCAmelCase_ ( self :Optional[int] )-> Union[str, Any]: A__ = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(pipe.scheduler , SCREAMING_SNAKE_CASE__ ) assert pipe.safety_checker is None A__ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None A__ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCAmelCase_ ( self :List[str] )-> str: A__ = self.dummy_cond_unet A__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__ ) A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 A__ = unet.half() A__ = vae.half() A__ = bert.half() # make sure here that pndm scheduler skips prk A__ = StableDiffusionPipeline( unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=self.dummy_extractor , ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = 'A painting of a squirrel eating a burger' A__ = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): def UpperCAmelCase_ ( self :int )-> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self :int )-> int: A__ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=SCREAMING_SNAKE_CASE__ ) A__ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = ( 'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle' ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with' ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and' ' children from bahnhof zoo, detailed ' ) A__ = 40_03_66_03_46 A__ = 7 # without safety guidance (sld_guidance_scale = 0) A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase_ ( self :Dict )-> List[str]: A__ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=SCREAMING_SNAKE_CASE__ ) A__ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = 'padme amidala taking a bath artwork, safe for work, no nudity' A__ = 27_34_97_17_55 A__ = 7 A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase_ ( self :List[Any] )-> Dict: A__ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) A__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = ( 'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.' ' leyendecker' ) A__ = 10_44_35_52_34 A__ = 12 A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) A__ = output.images A__ = image[0, -3:, -3:, -1] A__ = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
440
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a ={"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
652
0
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __UpperCAmelCase = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( a_ , unittest.TestCase ): """simple docstring""" lowerCamelCase : str =DebertaVaTokenizer lowerCamelCase : Tuple =DebertaVaTokenizerFast lowerCamelCase : List[str] =True lowerCamelCase : List[Any] =True def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase : Optional[int] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , unk_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase : Optional[int] ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : int = 'this is a test' __lowerCAmelCase : int = 'this is a test' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: """simple docstring""" __lowerCAmelCase : List[str] = '<pad>' __lowerCAmelCase : Dict = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: """simple docstring""" __lowerCAmelCase : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """[PAD]""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 3_00_01 ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_00_00 ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = ' \tHeLLo!how \n Are yoU? ' __lowerCAmelCase : List[str] = ['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on __lowerCAmelCase : Union[str, Any] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Any = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @unittest.skip("""There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.""" ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: """simple docstring""" pass @unittest.skip("""There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.""" ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: """simple docstring""" __lowerCAmelCase : List[Any] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : List[str] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __lowerCAmelCase : int = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[Any] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: """simple docstring""" __lowerCAmelCase : int = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Union[str, Any] = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __lowerCAmelCase : Tuple = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: """simple docstring""" __lowerCAmelCase : List[Any] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : List[str] = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __lowerCAmelCase : Any = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[str] = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Dict = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: """simple docstring""" __lowerCAmelCase : Tuple = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : List[Any] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __lowerCAmelCase : Any = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: """simple docstring""" __lowerCAmelCase : Tuple = ' \tHeLLo!how \n Are yoU? ' __lowerCAmelCase : Union[str, Any] = ['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on __lowerCAmelCase : List[str] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[str] = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : str = self.get_tokenizer() __lowerCAmelCase : Dict = self.get_rust_tokenizer() __lowerCAmelCase : Optional[int] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) __lowerCAmelCase : str = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[str] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Optional[int] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Tuple = self.get_rust_tokenizer() __lowerCAmelCase : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Tuple = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = 'This is a test' __lowerCAmelCase : int = [13, 1, 43_98, 25, 21, 12_89] __lowerCAmelCase : Tuple = ['▁', 'T', 'his', '▁is', '▁a', '▁test'] __lowerCAmelCase : str = ['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] __lowerCAmelCase : Union[str, Any] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Optional[Any] = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Union[str, Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Tuple = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[str] = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Union[str, Any] = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # fmt: off __lowerCAmelCase : Optional[int] = 'I was born in 92000, and this is falsé.' __lowerCAmelCase : List[Any] = [13, 1, 23, 3_86, 19, 5_61, 30_50, 15, 17, 48, 25, 82_56, 18, 1, 9] __lowerCAmelCase : int = ['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] __lowerCAmelCase : Optional[int] = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __lowerCAmelCase : Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : List[Any] = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Any = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : str = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : int = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> str: """simple docstring""" __lowerCAmelCase : Union[str, Any] = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Dict = tokenizer.encode("""sequence builders""" ) __lowerCAmelCase : Any = tokenizer.encode("""multi-sequence build""" ) __lowerCAmelCase : Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Any = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE__ ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE__ , ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: """simple docstring""" __lowerCAmelCase : Dict = {'input_ids': [[1, 3_98_67, 36, 1_93_90, 4_86, 27, 3_50_52, 8_14_36, 18, 6_06_85, 12_25, 7, 3_50_52, 8_14_36, 18, 93_67, 1_68_99, 18, 1_59_37, 53, 5_94, 7_73, 18, 1_62_87, 3_04_65, 36, 1_59_37, 6, 4_11_39, 38, 3_69_79, 6_07_63, 1_91, 6, 3_41_32, 99, 6, 5_05_38, 3_90, 4_32_30, 6, 3_41_32, 27_79, 2_08_50, 14, 6_99, 10_72, 11_94, 36, 3_82, 1_09_01, 53, 7, 6_99, 10_72, 20_84, 36, 2_04_22, 6_30, 53, 19, 1_05, 30_49, 18_96, 10_53, 1_68_99, 15_06, 11, 3_79_78, 42_43, 7, 12_37, 3_18_69, 2_00, 1_65_66, 6_54, 6, 3_50_52, 8_14_36, 7, 5_56_30, 1_35_93, 4, 2], [1, 26, 1_50_11, 13, 6_67, 8, 10_53, 18, 2_36_11, 12_37, 7_23_56, 1_28_20, 34, 10_41_34, 12_09, 35, 1_33_13, 66_27, 21, 2_02, 3_47, 7, 1_64, 23_99, 11, 46, 44_85, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 12_32, 28_64, 1_57_85, 1_49_51, 1_05, 5, 85_81, 12_50, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="""microsoft/deberta-v2-xlarge""" , revision="""ad6e42c1532ddf3a15c39246b63f5559d558b670""" , )
651
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = (UnCLIPScheduler,) def lowerCAmelCase ( self : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Any = { 'num_train_timesteps': 1_0_0_0, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**SCREAMING_SNAKE_CASE__) return config def lowerCAmelCase ( self : Optional[Any]): for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any]): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): for clip_sample_range in [1, 5, 1_0, 2_0]: self.check_over_configs(clip_sample_range=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any]): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): for time_step in [0, 5_0_0, 9_9_9]: for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Any = self.get_scheduler_config(variance_type='fixed_small_log') __lowerCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE__) assert torch.sum(torch.abs(scheduler._get_variance(0) - 1.00_00E-10)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7) - 0.0549625)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9) - 0.9994987)) < 1E-5 def lowerCAmelCase ( self : Any): __lowerCamelCase : Dict = self.scheduler_classes[0] __lowerCamelCase : List[str] = self.get_scheduler_config(variance_type='learned_range') __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = 0.5 assert scheduler._get_variance(1 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -10.1712790 < 1E-5 assert scheduler._get_variance(4_8_7 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -5.7998052 < 1E-5 assert scheduler._get_variance(9_9_9 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -0.0010011 < 1E-5 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : str = self.get_scheduler_config() __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = scheduler.timesteps __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter __lowerCamelCase : List[str] = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : int = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # 2. predict previous mean of sample x_t-1 __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Optional[Any] = pred_prev_sample __lowerCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 252.2682495) < 1E-2 assert abs(result_mean.item() - 0.3284743) < 1E-3 def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : List[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(2_5) __lowerCamelCase : int = scheduler.timesteps __lowerCamelCase : Tuple = self.dummy_model() __lowerCamelCase : Any = self.dummy_sample_deter __lowerCamelCase : Any = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if i + 1 == timesteps.shape[0]: __lowerCamelCase : Optional[Any] = None else: __lowerCamelCase : Union[str, Any] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __lowerCamelCase : int = scheduler.step( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Union[str, Any] = pred_prev_sample __lowerCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 258.2044983) < 1E-2 assert abs(result_mean.item() - 0.3362038) < 1E-3 def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Union[str, Any]): pass
652
0
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple) -> list[str]: '''simple docstring''' if nth_term == "": return [""] _lowercase : Tuple = int(lowerCamelCase__) _lowercase : Optional[Any] = int(lowerCamelCase__) _lowercase : list[str] = [] for temp in range(int(lowerCamelCase__)): series.append(F'''1 / {pow(temp + 1 , int(lowerCamelCase__))}''' if series else '1') return series if __name__ == "__main__": import doctest doctest.testmod() A = int(input('''Enter the last number (nth term) of the P-Series''')) A = int(input('''Enter the power for P-Series''')) print('''Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p''') print(p_series(nth_term, power))
125
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''swin2sr''' _UpperCAmelCase : Any = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=1 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : Tuple=1_8_0 ,SCREAMING_SNAKE_CASE__ : Any=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : int=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=8 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2.0 ,SCREAMING_SNAKE_CASE__ : Optional[int]=True ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-5 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Tuple=1.0 ,SCREAMING_SNAKE_CASE__ : int="1conv" ,SCREAMING_SNAKE_CASE__ : Optional[int]="pixelshuffle" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = image_size __lowerCamelCase : str = patch_size __lowerCamelCase : List[Any] = num_channels __lowerCamelCase : Dict = embed_dim __lowerCamelCase : Dict = depths __lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = num_heads __lowerCamelCase : Tuple = window_size __lowerCamelCase : Dict = mlp_ratio __lowerCamelCase : str = qkv_bias __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[Any] = attention_probs_dropout_prob __lowerCamelCase : List[Any] = drop_path_rate __lowerCamelCase : Optional[int] = hidden_act __lowerCamelCase : Dict = use_absolute_embeddings __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : str = initializer_range __lowerCamelCase : List[Any] = upscale __lowerCamelCase : List[Any] = img_range __lowerCamelCase : List[str] = resi_connection __lowerCamelCase : Union[str, Any] = upsampler
652
0
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 SCREAMING_SNAKE_CASE_ ( _a , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Optional[Any] =KandinskyVaaControlnetPipeline __lowerCAmelCase : Optional[Any] =['''image_embeds''', '''negative_image_embeds''', '''hint'''] __lowerCAmelCase : int =['''image_embeds''', '''negative_image_embeds''', '''hint'''] __lowerCAmelCase : List[Any] =[ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] __lowerCAmelCase : Tuple =False @property def UpperCamelCase__ ( self :Tuple): """simple docstring""" return 32 @property def UpperCamelCase__ ( self :List[Any]): """simple docstring""" return 32 @property def UpperCamelCase__ ( self :str): """simple docstring""" return self.time_input_dim @property def UpperCamelCase__ ( self :List[str]): """simple docstring""" return self.time_input_dim * 4 @property def UpperCamelCase__ ( self :List[str]): """simple docstring""" return 100 @property def UpperCamelCase__ ( self :Dict): """simple docstring""" torch.manual_seed(0) _lowercase ={ '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, } _lowercase =UNetaDConditionModel(**SCREAMING_SNAKE_CASE__) return model @property def UpperCamelCase__ ( self :Union[str, Any]): """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 UpperCamelCase__ ( self :Optional[Any]): """simple docstring""" torch.manual_seed(0) _lowercase =VQModel(**self.dummy_movq_kwargs) return model def UpperCamelCase__ ( self :Optional[Any]): """simple docstring""" _lowercase =self.dummy_unet _lowercase =self.dummy_movq _lowercase =DDIMScheduler( num_train_timesteps=1000, beta_schedule='linear', beta_start=0.0_0_0_8_5, beta_end=0.0_1_2, clip_sample=SCREAMING_SNAKE_CASE__, set_alpha_to_one=SCREAMING_SNAKE_CASE__, steps_offset=1, prediction_type='epsilon', thresholding=SCREAMING_SNAKE_CASE__, ) _lowercase ={ 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCamelCase__ ( self :int, snake_case :int, snake_case :Optional[int]=0): """simple docstring""" _lowercase =floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) _lowercase =floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(seed + 1)).to( SCREAMING_SNAKE_CASE__) # create hint _lowercase =floats_tensor((1, 3, 64, 64), rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) if str(SCREAMING_SNAKE_CASE__).startswith('mps'): _lowercase =torch.manual_seed(SCREAMING_SNAKE_CASE__) else: _lowercase =torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) _lowercase ={ '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 UpperCamelCase__ ( self :Optional[Any]): """simple docstring""" _lowercase ='cpu' _lowercase =self.get_dummy_components() _lowercase =self.pipeline_class(**SCREAMING_SNAKE_CASE__) _lowercase =pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) _lowercase =pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)) _lowercase =output.images _lowercase =pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__), return_dict=SCREAMING_SNAKE_CASE__, )[0] _lowercase =image[0, -3:, -3:, -1] _lowercase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowercase =np.array( [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5]) 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 SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self :int): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self :int): """simple docstring""" _lowercase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy') _lowercase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png') _lowercase =torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 2_5_5.0 _lowercase =hint.permute(2, 0, 1).unsqueeze(0) _lowercase =KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior', torch_dtype=torch.floataa) pipe_prior.to(SCREAMING_SNAKE_CASE__) _lowercase =KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth', torch_dtype=torch.floataa) _lowercase =pipeline.to(SCREAMING_SNAKE_CASE__) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) _lowercase ='A robot, 4k photo' _lowercase =torch.Generator(device='cuda').manual_seed(0) _lowercase =pipe_prior( SCREAMING_SNAKE_CASE__, generator=SCREAMING_SNAKE_CASE__, num_inference_steps=5, negative_prompt='', ).to_tuple() _lowercase =torch.Generator(device='cuda').manual_seed(0) _lowercase =pipeline( image_embeds=SCREAMING_SNAKE_CASE__, negative_image_embeds=SCREAMING_SNAKE_CASE__, hint=SCREAMING_SNAKE_CASE__, generator=SCREAMING_SNAKE_CASE__, num_inference_steps=100, output_type='np', ) _lowercase =output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__)
181
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__="pt" ) -> Dict: __lowerCamelCase : Any = {'add_prefix_space': True} if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not line.startswith(' ' ) else {} __lowerCamelCase : int = padding_side return tokenizer( [line] , max_length=lowerCamelCase__ , padding='max_length' if pad_to_max_length else None , truncation=lowerCamelCase__ , return_tensors=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , ) -> List[str]: __lowerCamelCase : List[str] = input_ids.ne(lowerCamelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]="train" ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[Any]="" ,): super().__init__() __lowerCamelCase : Optional[Any] = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.source') __lowerCamelCase : Any = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.target') __lowerCamelCase : List[Any] = self.get_char_lens(self.src_file) __lowerCamelCase : List[Any] = max_source_length __lowerCamelCase : List[str] = max_target_length assert min(self.src_lens) > 0, F"found empty line in {self.src_file}" __lowerCamelCase : Any = tokenizer __lowerCamelCase : Optional[int] = prefix if n_obs is not None: __lowerCamelCase : Dict = self.src_lens[:n_obs] __lowerCamelCase : str = src_lang __lowerCamelCase : Any = tgt_lang def __len__( self : Tuple): return len(self.src_lens) def __getitem__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Dict = index + 1 # linecache starts at 1 __lowerCamelCase : Any = self.prefix + linecache.getline(str(self.src_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') __lowerCamelCase : int = linecache.getline(str(self.tgt_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __lowerCamelCase : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer ) __lowerCamelCase : Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer __lowerCamelCase : List[str] = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_source_length ,'right') __lowerCamelCase : Any = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_target_length ,'right') __lowerCamelCase : List[Any] = source_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = target_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : int): return [len(SCREAMING_SNAKE_CASE__) for x in Path(SCREAMING_SNAKE_CASE__).open().readlines()] def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[Any] = torch.stack([x['input_ids'] for x in batch]) __lowerCamelCase : Any = torch.stack([x['attention_mask'] for x in batch]) __lowerCamelCase : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch]) __lowerCamelCase : Optional[int] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch a =getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return list(itertools.chain.from_iterable(lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: __lowerCamelCase : str = get_git_info() save_json(lowerCamelCase__ , os.path.join(lowerCamelCase__ , 'git_log.json' ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=4 , **lowerCamelCase__ ) -> List[str]: with open(lowerCamelCase__ , 'w' ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=lowerCamelCase__ , **lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: with open(lowerCamelCase__ ) as f: return json.load(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: __lowerCamelCase : str = git.Repo(search_parent_directories=lowerCamelCase__ ) __lowerCamelCase : Any = { 'repo_id': str(lowerCamelCase__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List: return list(map(lowerCamelCase__ , lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: with open(lowerCamelCase__ , 'wb' ) as f: return pickle.dump(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: def remove_articles(lowerCamelCase__ ): return re.sub(R'\b(a|an|the)\b' , ' ' , lowerCamelCase__ ) def white_space_fix(lowerCamelCase__ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase__ ): __lowerCamelCase : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : str = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Optional[int] = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) & Counter(lowerCamelCase__ ) __lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 __lowerCamelCase : List[Any] = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : int = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: return normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) __lowerCamelCase : Dict = 0 for hypo, pred in zip(lowerCamelCase__ , lowerCamelCase__ ): em += exact_match_score(lowerCamelCase__ , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: em /= len(lowerCamelCase__ ) return {"em": em} def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return model_prefix.startswith('rag' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __lowerCamelCase : List[str] = 'dropout_rate' for p in extra_params: if getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if not hasattr(lowerCamelCase__ , lowerCamelCase__ ) and not hasattr(lowerCamelCase__ , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) continue __lowerCamelCase : List[Any] = p if hasattr(lowerCamelCase__ , lowerCamelCase__ ) else equivalent_param[p] setattr(lowerCamelCase__ , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) return hparams, config
652
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class lowerCamelCase__ ( snake_case ): SCREAMING_SNAKE_CASE = '''swin2sr''' SCREAMING_SNAKE_CASE = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self ,A=64 ,A=1 ,A=3 ,A=180 ,A=[6, 6, 6, 6, 6, 6] ,A=[6, 6, 6, 6, 6, 6] ,A=8 ,A=2.0 ,A=True ,A=0.0 ,A=0.0 ,A=0.1 ,A="gelu" ,A=False ,A=0.02 ,A=1e-5 ,A=2 ,A=1.0 ,A="1conv" ,A="pixelshuffle" ,**A ,): super().__init__(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = embed_dim UpperCAmelCase = depths UpperCAmelCase = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = num_heads UpperCAmelCase = window_size UpperCAmelCase = mlp_ratio UpperCAmelCase = qkv_bias UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = drop_path_rate UpperCAmelCase = hidden_act UpperCAmelCase = use_absolute_embeddings UpperCAmelCase = layer_norm_eps UpperCAmelCase = initializer_range UpperCAmelCase = upscale UpperCAmelCase = img_range UpperCAmelCase = resi_connection UpperCAmelCase = upsampler
341
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a =logging.get_logger(__name__) # General docstring a ="""MobileNetV1Config""" # Base docstring a ="""google/mobilenet_v1_1.0_224""" a =[1, 1024, 7, 7] # Image classification docstring a ="""google/mobilenet_v1_1.0_224""" a ="""tabby, tabby cat""" a =[ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> str: __lowerCamelCase : str = {} if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = model.mobilenet_va else: __lowerCamelCase : List[str] = model __lowerCamelCase : List[Any] = 'MobilenetV1/Conv2d_0/' __lowerCamelCase : List[Any] = backbone.conv_stem.convolution.weight __lowerCamelCase : List[str] = backbone.conv_stem.normalization.bias __lowerCamelCase : Tuple = backbone.conv_stem.normalization.weight __lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean __lowerCamelCase : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(1_3 ): __lowerCamelCase : Any = i + 1 __lowerCamelCase : Union[str, Any] = i * 2 __lowerCamelCase : Optional[Any] = backbone.layer[pt_index] __lowerCamelCase : Optional[int] = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" __lowerCamelCase : Tuple = pointer.convolution.weight __lowerCamelCase : Optional[Any] = pointer.normalization.bias __lowerCamelCase : Union[str, Any] = pointer.normalization.weight __lowerCamelCase : List[str] = pointer.normalization.running_mean __lowerCamelCase : Union[str, Any] = pointer.normalization.running_var __lowerCamelCase : int = backbone.layer[pt_index + 1] __lowerCamelCase : Union[str, Any] = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" __lowerCamelCase : Optional[Any] = pointer.convolution.weight __lowerCamelCase : Any = pointer.normalization.bias __lowerCamelCase : str = pointer.normalization.weight __lowerCamelCase : Dict = pointer.normalization.running_mean __lowerCamelCase : List[str] = pointer.normalization.running_var if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __lowerCamelCase : Any = model.classifier.weight __lowerCamelCase : int = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __lowerCamelCase : List[str] = tf.train.list_variables(lowerCamelCase__ ) __lowerCamelCase : List[str] = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) __lowerCamelCase : Any = tf.train.load_variable(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[Any] = array # Build TF to PyTorch weights loading map __lowerCamelCase : Tuple = _build_tf_to_pytorch_map(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue __lowerCamelCase : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __lowerCamelCase : List[str] = np.transpose(lowerCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __lowerCamelCase : Any = array.squeeze().transpose() else: __lowerCamelCase : Tuple = np.transpose(lowerCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) __lowerCamelCase : Optional[Any] = torch.from_numpy(lowerCamelCase__ ) tf_weights.pop(lowerCamelCase__ , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp' , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp_1' , lowerCamelCase__ ) tf_weights.pop(name + '/ExponentialMovingAverage' , lowerCamelCase__ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: __lowerCamelCase , __lowerCamelCase : int = features.shape[-2:] __lowerCamelCase , __lowerCamelCase : List[str] = conv_layer.stride __lowerCamelCase , __lowerCamelCase : str = conv_layer.kernel_size if in_height % stride_height == 0: __lowerCamelCase : Optional[int] = max(kernel_height - stride_height , 0 ) else: __lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __lowerCamelCase : List[str] = max(kernel_width - stride_width , 0 ) else: __lowerCamelCase : List[str] = max(kernel_width - (in_width % stride_width) , 0 ) __lowerCamelCase : List[str] = pad_along_width // 2 __lowerCamelCase : Optional[int] = pad_along_width - pad_left __lowerCamelCase : Any = pad_along_height // 2 __lowerCamelCase : List[Any] = pad_along_height - pad_top __lowerCamelCase : Union[str, Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(lowerCamelCase__ , lowerCamelCase__ , 'constant' , 0.0 ) class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[bool or str] = True ,): super().__init__() __lowerCamelCase : Dict = config if in_channels % groups != 0: raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups.") if out_channels % groups != 0: raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups.") __lowerCamelCase : Optional[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2) __lowerCamelCase : Optional[int] = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__ ,padding_mode='zeros' ,) if use_normalization: __lowerCamelCase : Optional[int] = nn.BatchNormad( num_features=SCREAMING_SNAKE_CASE__ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=SCREAMING_SNAKE_CASE__ ,track_running_stats=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Dict = None if use_activation: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = ACTaFN[use_activation] elif isinstance(config.hidden_act ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = ACTaFN[config.hidden_act] else: __lowerCamelCase : List[str] = config.hidden_act else: __lowerCamelCase : List[str] = None def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): if self.config.tf_padding: __lowerCamelCase : Any = apply_tf_padding(SCREAMING_SNAKE_CASE__ ,self.convolution) __lowerCamelCase : Optional[int] = self.convolution(SCREAMING_SNAKE_CASE__) if self.normalization is not None: __lowerCamelCase : Dict = self.normalization(SCREAMING_SNAKE_CASE__) if self.activation is not None: __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return features class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = MobileNetVaConfig _UpperCAmelCase : List[str] = load_tf_weights_in_mobilenet_va _UpperCAmelCase : List[str] = '''mobilenet_v1''' _UpperCAmelCase : Any = '''pixel_values''' _UpperCAmelCase : int = False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[nn.Linear, nn.Convad]): if isinstance(SCREAMING_SNAKE_CASE__ ,(nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ ,nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : bool = True): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = config __lowerCamelCase : Optional[int] = 3_2 __lowerCamelCase : List[str] = max(int(depth * config.depth_multiplier) ,config.min_depth) __lowerCamelCase : Optional[Any] = MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=config.num_channels ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=2 ,) __lowerCamelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __lowerCamelCase : str = nn.ModuleList() for i in range(1_3): __lowerCamelCase : str = out_channels if strides[i] == 2 or i == 0: depth *= 2 __lowerCamelCase : str = max(int(depth * config.depth_multiplier) ,config.min_depth) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=strides[i] ,groups=SCREAMING_SNAKE_CASE__ ,)) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,)) __lowerCamelCase : Optional[int] = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') __lowerCamelCase : Optional[Any] = self.conv_stem(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Any = all_hidden_states + (hidden_states,) __lowerCamelCase : Optional[Any] = hidden_states if self.pooler is not None: __lowerCamelCase : Tuple = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__) ,start_dim=1) else: __lowerCamelCase : List[str] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = config.num_labels __lowerCamelCase : Optional[Any] = MobileNetVaModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __lowerCamelCase : Any = nn.Dropout(config.classifier_dropout_prob ,inplace=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Optional[int] = self.mobilenet_va(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] = self.classifier(self.dropout(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : int = 'single_label_classification' else: __lowerCamelCase : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : Tuple = MSELoss() if self.num_labels == 1: __lowerCamelCase : int = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : Union[str, Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : List[str] = CrossEntropyLoss() __lowerCamelCase : List[str] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : int = BCEWithLogitsLoss() __lowerCamelCase : int = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states ,)
652
0
'''simple docstring''' import math import random def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ) -> float: '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value lowercase__ = 0.02 def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> float: '''simple docstring''' snake_case : Union[str, Any] = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(lowerCamelCase__ ): # Forward propagation snake_case : Union[str, Any] = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? snake_case : List[str] = (expected / 100) - layer_a # Error delta snake_case : Optional[Any] = layer_1_error * sigmoid_function(lowerCamelCase__ , lowerCamelCase__ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() lowercase__ = int(input("Expected value: ")) lowercase__ = int(input("Number of propagations: ")) print(forward_propagation(expected, number_propagations))
638
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = cva.getAffineTransform(lowerCamelCase__ , lowerCamelCase__ ) return cva.warpAffine(lowerCamelCase__ , lowerCamelCase__ , (rows, cols) ) if __name__ == "__main__": # read original image a =cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value a =cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a , a =gray_img.shape # set different points to rotate image a =np.array([[50, 50], [200, 50], [50, 200]], np.floataa) a =np.array([[10, 100], [200, 50], [100, 250]], np.floataa) a =np.array([[50, 50], [150, 50], [120, 200]], np.floataa) a =np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list a =[ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a =plt.figure(1) a =["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
652
0
UpperCAmelCase : Dict = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase : Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase : Tuple = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def __lowerCamelCase ( lowerCamelCase__ : Dict , lowerCamelCase__ : Dict , lowerCamelCase__ : Any ): '''simple docstring''' assert len(str(lowerCamelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: lowerCamelCase = year // 100 lowerCamelCase = (5 * (century % 4) + 2) % 7 lowerCamelCase = year % 100 lowerCamelCase = centurian % 12 lowerCamelCase = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 lowerCamelCase = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) lowerCamelCase = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
457
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : List[str] = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCamelCase__ ) if number < 1: __lowerCamelCase : int = F"Input value of [number={number}] must be > 0" raise ValueError(lowerCamelCase__ ) elif number == 1: return 3 elif number == 2: return 5 else: __lowerCamelCase : Any = int(math.log(number // 3 , 2 ) ) + 2 __lowerCamelCase : List[Any] = [3, 5] __lowerCamelCase : Union[str, Any] = 2 __lowerCamelCase : List[str] = 3 for block in range(1 , lowerCamelCase__ ): for _ in range(lowerCamelCase__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): a =0 try: a =proth(number) except ValueError: print(F"""ValueError: there is no {number}th Proth number""") continue print(F"""The {number}th Proth number: {value}""")
652
0
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets _a : str = datasets.logging.get_logger(__name__) _a : Optional[Any] = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel's Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = \"{COMET}: A Neural Framework for {MT} Evaluation\", author = \"Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon\", booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\", month = nov, year = \"2020\", address = \"Online\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\", pages = \"2685--2702\", } """ _a : int = """\ Crosslingual 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). With 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. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. """ _a : List[str] = """ COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric('comet') >>> # comet_metric = load_metric('comet', 'wmt20-comet-da') # you can also choose which model to use >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"] >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"] >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results[\"scores\"]]) [0.19, 0.92] """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): def lowerCamelCase__ ( self ): '''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 lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if self.config_name == "default": __lowerCAmelCase = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) ) else: __lowerCAmelCase = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=None,__SCREAMING_SNAKE_CASE=False ): '''simple docstring''' if gpus is None: __lowerCAmelCase = 1 if torch.cuda.is_available() else 0 __lowerCAmelCase = {'src': sources, 'mt': predictions, 'ref': references} __lowerCAmelCase = [dict(zip(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) ) for t in zip(*data.values() )] __lowerCAmelCase = self.scorer.predict(SCREAMING_SNAKE_CASE__,gpus=SCREAMING_SNAKE_CASE__,progress_bar=SCREAMING_SNAKE_CASE__ ) return {"mean_score": mean_score, "scores": scores}
689
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class A_ ( unittest.TestCase ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=7 ,SCREAMING_SNAKE_CASE__ : Any=3 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0 ,SCREAMING_SNAKE_CASE__ : int=4_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[str]=1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : Tuple=True ,): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCamelCase : List[Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} __lowerCamelCase : str = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : int = num_channels __lowerCamelCase : Dict = min_resolution __lowerCamelCase : Tuple = max_resolution __lowerCamelCase : Dict = do_resize __lowerCamelCase : List[Any] = size __lowerCamelCase : Tuple = do_normalize __lowerCamelCase : Any = image_mean __lowerCamelCase : List[str] = image_std __lowerCamelCase : List[Any] = do_rescale __lowerCamelCase : str = rescale_factor __lowerCamelCase : Tuple = do_pad def lowerCAmelCase ( self : Dict): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=False): if not batched: __lowerCamelCase : Optional[Any] = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ ,Image.Image): __lowerCamelCase , __lowerCamelCase : Any = image.size else: __lowerCamelCase , __lowerCamelCase : Any = image.shape[1], image.shape[2] if w < h: __lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w) __lowerCamelCase : Tuple = self.size['shortest_edge'] elif w > h: __lowerCamelCase : Union[str, Any] = self.size['shortest_edge'] __lowerCamelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h) else: __lowerCamelCase : List[Any] = self.size['shortest_edge'] __lowerCamelCase : Optional[int] = self.size['shortest_edge'] else: __lowerCamelCase : List[str] = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase : List[Any] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) __lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[0])[0] __lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[1])[1] return expected_height, expected_width @require_torch @require_vision class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[int] = DetaImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = DetaImageProcessingTester(self) @property def lowerCAmelCase ( self : Any): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_std')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_rescale')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_pad')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'size')) def lowerCAmelCase ( self : str): __lowerCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size ,{'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}) self.assertEqual(image_processor.do_pad ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): pass def lowerCAmelCase ( self : List[str]): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random PIL images __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,Image.Image) # Test not batched input __lowerCamelCase : List[Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : str): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,np.ndarray) # Test not batched input __lowerCamelCase : Tuple = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : int): # Initialize image_processing __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,torch.Tensor) # Test not batched input __lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) @slow def lowerCAmelCase ( self : Optional[Any]): # prepare image and target __lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r') as f: __lowerCamelCase : List[str] = json.loads(f.read()) __lowerCamelCase : Union[str, Any] = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them __lowerCamelCase : Optional[int] = DetaImageProcessor() __lowerCamelCase : int = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Dict = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : int = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : Tuple = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : List[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify orig_size __lowerCamelCase : str = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : int = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__)) @slow def lowerCAmelCase ( self : str): # prepare image, target and masks_path __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r') as f: __lowerCamelCase : Tuple = json.loads(f.read()) __lowerCamelCase : List[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} __lowerCamelCase : Optional[int] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them __lowerCamelCase : List[str] = DetaImageProcessor(format='coco_panoptic') __lowerCamelCase : Optional[Any] = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,masks_path=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : Tuple = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : int = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : int = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify masks __lowerCamelCase : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,SCREAMING_SNAKE_CASE__) # verify orig_size __lowerCamelCase : Any = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : Any = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
652
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase__ : Optional[int] = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : int = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Dict = [ '''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 UpperCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
410
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_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[Any] = KandinskyVaaControlnetPipeline _UpperCAmelCase : Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : int = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : List[Any] = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _UpperCAmelCase : Tuple = False @property def lowerCAmelCase ( self : Tuple): return 3_2 @property def lowerCAmelCase ( self : List[Any]): return 3_2 @property def lowerCAmelCase ( self : str): return self.time_input_dim @property def lowerCAmelCase ( self : List[str]): return self.time_input_dim * 4 @property def lowerCAmelCase ( self : List[str]): return 1_0_0 @property def lowerCAmelCase ( self : Dict): torch.manual_seed(0) __lowerCamelCase : 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, } __lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__) return model @property def lowerCAmelCase ( self : Union[str, Any]): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Optional[Any]): torch.manual_seed(0) __lowerCamelCase : int = VQModel(**self.dummy_movq_kwargs) return model def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = self.dummy_unet __lowerCamelCase : List[Any] = self.dummy_movq __lowerCamelCase : str = DDIMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='linear' ,beta_start=0.00085 ,beta_end=0.012 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Dict = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=0): __lowerCamelCase : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1)).to( SCREAMING_SNAKE_CASE__) # create hint __lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) if str(SCREAMING_SNAKE_CASE__).startswith('mps'): __lowerCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 6_4, 'width': 6_4, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = 'cpu' __lowerCamelCase : Tuple = self.get_dummy_components() __lowerCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = output.images __lowerCamelCase : Tuple = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) ,return_dict=SCREAMING_SNAKE_CASE__ ,)[0] __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : List[str] = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]) assert ( np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : int): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy') __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png') __lowerCamelCase : Tuple = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 255.0 __lowerCamelCase : str = hint.permute(2 ,0 ,1).unsqueeze(0) __lowerCamelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa) pipe_prior.to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' ,torch_dtype=torch.floataa) __lowerCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE__) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 'A robot, 4k photo' __lowerCamelCase : List[str] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe_prior( SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple() __lowerCamelCase : Optional[Any] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase : Any = pipeline( image_embeds=SCREAMING_SNAKE_CASE__ ,negative_image_embeds=SCREAMING_SNAKE_CASE__ ,hint=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
652
0
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( a_ ): """simple docstring""" a = (DEISMultistepScheduler,) a = (('''num_inference_steps''', 25),) def A ( self : Any , **SCREAMING_SNAKE_CASE : int): _A : Dict = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**SCREAMING_SNAKE_CASE__) return config def A ( self : Optional[int] , SCREAMING_SNAKE_CASE : Union[str, Any]=0 , **SCREAMING_SNAKE_CASE : List[str]): _A : Optional[Any] = dict(self.forward_default_kwargs) _A : List[str] = kwargs.pop('num_inference_steps' , SCREAMING_SNAKE_CASE__) _A : Dict = self.dummy_sample _A : List[Any] = 0.1 * sample _A : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _A : Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) _A : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals _A : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__) _A : Tuple = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals _A : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] _A : Any = sample, sample for t in range(SCREAMING_SNAKE_CASE__ , time_step + scheduler.config.solver_order + 1): _A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample _A : Any = new_scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def A ( self : str): pass def A ( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any]=0 , **SCREAMING_SNAKE_CASE : int): _A : str = dict(self.forward_default_kwargs) _A : Any = kwargs.pop('num_inference_steps' , SCREAMING_SNAKE_CASE__) _A : str = self.dummy_sample _A : Dict = 0.1 * sample _A : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _A : Dict = self.get_scheduler_config() _A : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals (must be after setting timesteps) _A : str = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__) _A : int = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # copy over dummy past residual (must be after setting timesteps) _A : Any = dummy_past_residuals[: new_scheduler.config.solver_order] _A : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample _A : int = new_scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def A ( self : Any , SCREAMING_SNAKE_CASE : int=None , **SCREAMING_SNAKE_CASE : Tuple): if scheduler is None: _A : Dict = self.scheduler_classes[0] _A : int = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) _A : int = scheduler_class(**SCREAMING_SNAKE_CASE__) _A : Optional[Any] = self.scheduler_classes[0] _A : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__) _A : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) _A : Optional[int] = 10 _A : Union[str, Any] = self.dummy_model() _A : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) for i, t in enumerate(scheduler.timesteps): _A : Tuple = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) _A : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).prev_sample return sample def A ( self : Any): _A : Optional[Any] = dict(self.forward_default_kwargs) _A : List[Any] = kwargs.pop('num_inference_steps' , SCREAMING_SNAKE_CASE__) for scheduler_class in self.scheduler_classes: _A : List[Any] = self.get_scheduler_config() _A : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__) _A : Optional[int] = self.dummy_sample _A : List[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE__ , 'set_timesteps'): scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE__ , 'set_timesteps'): _A : List[str] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _A : Any = [residual + 0.2, residual + 0.15, residual + 0.10] _A : Union[str, Any] = dummy_past_residuals[: scheduler.config.solver_order] _A : Optional[int] = scheduler.timesteps[5] _A : Optional[Any] = scheduler.timesteps[6] _A : Any = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample _A : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def A ( self : Tuple): # make sure that iterating over schedulers with same config names gives same results # for defaults _A : Tuple = DEISMultistepScheduler(**self.get_scheduler_config()) _A : List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__) _A : Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2_3916) < 1e-3 _A : Union[str, Any] = DPMSolverSinglestepScheduler.from_config(scheduler.config) _A : Optional[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config) _A : Tuple = UniPCMultistepScheduler.from_config(scheduler.config) _A : str = DEISMultistepScheduler.from_config(scheduler.config) _A : Tuple = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__) _A : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2_3916) < 1e-3 def A ( self : str): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def A ( self : List[str]): self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , algorithm_type='deis' , solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , ) def A ( self : Union[str, Any]): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def A ( self : List[str]): for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , algorithm_type=SCREAMING_SNAKE_CASE__ , ) _A : Tuple = self.full_loop( solver_order=SCREAMING_SNAKE_CASE__ , solver_type=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , algorithm_type=SCREAMING_SNAKE_CASE__ , ) assert not torch.isnan(SCREAMING_SNAKE_CASE__).any(), "Samples have nan numbers" def A ( self : int): self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__) def A ( self : List[str]): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE__ , time_step=0) def A ( self : Dict): _A : List[Any] = self.full_loop() _A : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.2_3916) < 1e-3 def A ( self : Dict): _A : int = self.full_loop(prediction_type='v_prediction') _A : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_mean.item() - 0.091) < 1e-3 def A ( self : Optional[int]): _A : Union[str, Any] = self.scheduler_classes[0] _A : Tuple = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE__ , dynamic_thresholding_ratio=0) _A : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE__) _A : Optional[Any] = 10 _A : Optional[int] = self.dummy_model() _A : Union[str, Any] = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) for i, t in enumerate(scheduler.timesteps): _A : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) _A : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).prev_sample assert sample.dtype == torch.floataa
128
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : _UpperCAmelCase : int = XGLMConfig _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Tuple = '''gelu''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 ,SCREAMING_SNAKE_CASE__ : Tuple=7 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=9_9 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : Tuple=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,): __lowerCamelCase : List[str] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_input_mask __lowerCamelCase : str = use_labels __lowerCamelCase : Any = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : List[str] = ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : Tuple = activation_dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Any = None __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 2 __lowerCamelCase : Dict = 1 def lowerCAmelCase ( self : Any): return XGLMConfig.from_pretrained('facebook/xglm-564M') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) ,clip_value_min=0 ,clip_value_max=3) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : int = self.get_config() __lowerCamelCase : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[Any]): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=SCREAMING_SNAKE_CASE__ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : int): __lowerCamelCase : int = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : str = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : str = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _UpperCAmelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else () _UpperCAmelCase : str = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Tuple = TFXGLMModelTester(self) __lowerCamelCase : int = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,n_embd=3_7) def lowerCAmelCase ( self : List[Any]): self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : str): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.') def lowerCAmelCase ( self : Union[str, Any]): super().test_resize_token_embeddings() @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True): __lowerCamelCase : Any = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]] ,dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __lowerCamelCase : Optional[Any] = [2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1] # fmt: on __lowerCamelCase : int = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') tf.random.set_seed(0) __lowerCamelCase : Optional[Any] = tokenizer('Today is a nice day and' ,return_tensors='tf') __lowerCamelCase : List[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0'): __lowerCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,seed=[7, 0]) __lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = 'left' # use different length sentences to test batching __lowerCamelCase : List[str] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __lowerCamelCase : List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='tf' ,padding=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['input_ids'] __lowerCamelCase : Dict = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=inputs['attention_mask'] ,max_new_tokens=1_2) __lowerCamelCase : Tuple = tokenizer(sentences[0] ,return_tensors='tf').input_ids __lowerCamelCase : List[str] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : Any = tokenizer(sentences[1] ,return_tensors='tf').input_ids __lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tokenizer.decode(output_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[non_padded_sentence, padded_sentence])
652
0
"""simple docstring""" def a_ ( __a , __a ): A__ = len(lowerCamelCase__ ) A__ = len(lowerCamelCase__ ) A__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ = True for i in range(lowerCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ = True if a[i].islower(): A__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
571
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
652
0
'''simple docstring''' from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def UpperCamelCase ( _lowerCamelCase : Optional[Any] ): if isinstance(lowerCamelCase__ , collections.abc.Iterable ): return x return (x, x) @require_tf class UpperCAmelCase : def UpperCAmelCase_ ( self :int , lowercase_ :Optional[Any] , lowercase_ :Dict )-> int: pass def UpperCAmelCase_ ( self :Optional[int] )-> Dict: pass def UpperCAmelCase_ ( self :Optional[int] )-> Optional[int]: pass def UpperCAmelCase_ ( self :Union[str, Any] , lowercase_ :List[Any] , lowercase_ :Dict , lowercase_ :Optional[int] , lowercase_ :List[Any] , lowercase_ :List[str]=None , **lowercase_ :Dict )-> Optional[int]: A__ = VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A__ = model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def UpperCAmelCase_ ( self :Union[str, Any] , lowercase_ :int , lowercase_ :List[Any] , lowercase_ :Union[str, Any] , lowercase_ :Optional[Any] , lowercase_ :Optional[Any]=None , **lowercase_ :Any )-> List[Any]: A__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__ , text_model=SCREAMING_SNAKE_CASE__ ) A__ = model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def UpperCAmelCase_ ( self :List[Any] , lowercase_ :Union[str, Any] , lowercase_ :int , lowercase_ :str , lowercase_ :Any , lowercase_ :str=None , **lowercase_ :Any )-> Dict: A__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = {'vision_model': vision_model, 'text_model': text_model} A__ = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE__ ) A__ = model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def UpperCAmelCase_ ( self :List[str] , lowercase_ :str , lowercase_ :Tuple , lowercase_ :List[str] , lowercase_ :Optional[int] , lowercase_ :int=None , **lowercase_ :Any )-> str: A__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__ , text_model=SCREAMING_SNAKE_CASE__ ) A__ = model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) A__ = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) A__ = after_output[0].numpy() A__ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1E-5 ) def UpperCAmelCase_ ( self :Optional[int] , lowercase_ :str , lowercase_ :Optional[Any] , lowercase_ :Optional[Any] , lowercase_ :Dict , lowercase_ :Optional[Any]=None , **lowercase_ :Optional[Any] )-> Optional[Any]: A__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__ , text_model=SCREAMING_SNAKE_CASE__ ) A__ = model( input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_attentions=SCREAMING_SNAKE_CASE__ ) A__ = output.vision_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) A__ = to_atuple(vision_model.config.image_size ) A__ = to_atuple(vision_model.config.patch_size ) A__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) A__ = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) A__ = output.text_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def UpperCAmelCase_ ( self :Optional[int] , lowercase_ :np.ndarray , lowercase_ :np.ndarray , lowercase_ :float )-> Dict: A__ = np.abs((a - b) ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , F"Difference between torch and flax is {diff} (>= {tol})." ) def UpperCAmelCase_ ( self :List[str] )-> Union[str, Any]: A__ = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Any )-> List[str]: A__ = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :List[str] )-> Tuple: A__ = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :List[str] )-> str: A__ = self.prepare_config_and_inputs() self.check_save_load(**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Optional[Any] )-> Optional[Any]: A__ = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE__ ) @slow def UpperCAmelCase_ ( self :Tuple )-> int: A__ = self.get_pretrained_model_and_inputs() A__ = model_a(**SCREAMING_SNAKE_CASE__ ) A__ = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = model_a(**SCREAMING_SNAKE_CASE__ ) A__ = after_outputs[0].numpy() A__ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1E-5 ) @require_tf class UpperCAmelCase ( UpperCamelCase__ , unittest.TestCase ): def UpperCAmelCase_ ( self :str )-> List[str]: A__ = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) A__ = 13 A__ = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) A__ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) A__ = random_attention_mask([batch_size, 4] ) A__ = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def UpperCAmelCase_ ( self :int , lowercase_ :int , lowercase_ :List[Any] )-> Union[str, Any]: A__ = TFViTModel(SCREAMING_SNAKE_CASE__ , name="vision_model" ) A__ = TFBertModel(SCREAMING_SNAKE_CASE__ , name="text_model" ) return vision_model, text_model def UpperCAmelCase_ ( self :Any )-> Dict: A__ = TFViTModelTester(self ) A__ = TFBertModelTester(self ) A__ = vit_model_tester.prepare_config_and_inputs() A__ = bert_model_tester.prepare_config_and_inputs() A__ = vision_config_and_inputs ( A__ ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class UpperCAmelCase ( UpperCamelCase__ , unittest.TestCase ): def UpperCAmelCase_ ( self :Dict )-> List[str]: # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. A__ = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) A__ = 13 A__ = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) A__ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) A__ = random_attention_mask([batch_size, 4] ) A__ = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def UpperCAmelCase_ ( self :Dict , lowercase_ :List[Any] , lowercase_ :Tuple , lowercase_ :Dict , lowercase_ :List[str] , lowercase_ :str=None , **lowercase_ :Dict )-> Tuple: A__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = TFVisionTextDualEncoderModel(vision_model=SCREAMING_SNAKE_CASE__ , text_model=SCREAMING_SNAKE_CASE__ ) A__ = model( input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_attentions=SCREAMING_SNAKE_CASE__ ) A__ = output.vision_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) A__ = to_atuple(vision_model.config.image_size ) A__ = to_atuple(vision_model.config.patch_size ) A__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) A__ = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) A__ = output.text_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def UpperCAmelCase_ ( self :Optional[int] , lowercase_ :Optional[int] , lowercase_ :Optional[int] )-> str: A__ = TFDeiTModel(SCREAMING_SNAKE_CASE__ , name="vision_model" ) A__ = TFRobertaModel(SCREAMING_SNAKE_CASE__ , name="text_model" ) return vision_model, text_model def UpperCAmelCase_ ( self :List[Any] )-> Dict: A__ = TFDeiTModelTester(self ) A__ = TFRobertaModelTester(self ) A__ = vit_model_tester.prepare_config_and_inputs() A__ = bert_model_tester.prepare_config_and_inputs() A__ = vision_config_and_inputs ( A__ ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class UpperCAmelCase ( UpperCamelCase__ , unittest.TestCase ): def UpperCAmelCase_ ( self :Any )-> Any: A__ = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) A__ = 13 A__ = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) A__ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) A__ = random_attention_mask([batch_size, 4] ) A__ = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def UpperCAmelCase_ ( self :int , lowercase_ :str , lowercase_ :Optional[int] )-> Tuple: A__ = TFCLIPVisionModel(SCREAMING_SNAKE_CASE__ , name="vision_model" ) A__ = TFBertModel(SCREAMING_SNAKE_CASE__ , name="text_model" ) return vision_model, text_model def UpperCAmelCase_ ( self :List[Any] )-> Optional[Any]: A__ = TFCLIPVisionModelTester(self ) A__ = TFBertModelTester(self ) A__ = clip_model_tester.prepare_config_and_inputs() A__ = bert_model_tester.prepare_config_and_inputs() A__ = vision_config_and_inputs ( A__ ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class UpperCAmelCase ( unittest.TestCase ): @slow def UpperCAmelCase_ ( self :int )-> Tuple: A__ = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=SCREAMING_SNAKE_CASE__ ) A__ = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) A__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) A__ = processor( text=["una foto di un gatto", "una foto di un cane"] , images=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) A__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) A__ = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
440
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a =logging.get_logger(__name__) # General docstring a ="""RegNetConfig""" # Base docstring a ="""facebook/regnet-y-040""" a =[1, 1088, 7, 7] # Image classification docstring a ="""facebook/regnet-y-040""" a ="""tabby, tabby cat""" a =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : Optional[str] = "relu" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2) __lowerCamelCase : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,strides=SCREAMING_SNAKE_CASE__ ,padding='VALID' ,groups=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution' ,) __lowerCamelCase : int = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') __lowerCamelCase : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Dict): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = config.num_channels __lowerCamelCase : Dict = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='embedder' ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__)[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,strides=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution') __lowerCamelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False): return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__) ,training=SCREAMING_SNAKE_CASE__) class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') __lowerCamelCase : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='relu' ,name='attention.0'), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='sigmoid' ,name='attention.2'), ] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__) for layer_module in self.attention: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = hidden_state * pooled return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[Any]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = max(1 ,out_channels // config.groups_width) __lowerCamelCase : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.2'), ] __lowerCamelCase : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : int = hidden_state for layer_module in self.layers: __lowerCamelCase : List[str] = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : int = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1 __lowerCamelCase : Tuple = max(1 ,out_channels // config.groups_width) __lowerCamelCase : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ ,reduced_channels=int(round(in_channels / 4)) ,name='layer.2'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.3'), ] __lowerCamelCase : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[int] = hidden_state for layer_module in self.layers: __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : Any = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCamelCase : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='layers.0'), *[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,name=F"layers.{i+1}") for i in range(depth - 1)], ] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): for layer_module in self.layers: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='stages.0' ,)) __lowerCamelCase : Optional[int] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:])): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__ ,name=F"stages.{i+1}")) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Optional[Any] = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__) @keras_serializable class A_ ( tf.keras.layers.Layer ): _UpperCAmelCase : List[Any] = RegNetConfig def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = config __lowerCamelCase : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ ,name='embedder') __lowerCamelCase : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ ,name='encoder') __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') @unpack_inputs def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,): __lowerCamelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = encoder_outputs[0] __lowerCamelCase : int = self.pooler(SCREAMING_SNAKE_CASE__) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) __lowerCamelCase : str = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) for h in encoder_outputs[1]]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : Optional[int] = '''regnet''' _UpperCAmelCase : List[Any] = '''pixel_values''' @property def lowerCAmelCase ( self : int): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) ,dtype=tf.floataa)} a =r""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : int=False ,): __lowerCamelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__ ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : str): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = config.num_labels __lowerCamelCase : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') # classification head __lowerCamelCase : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='classifier.1') if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Any=False ,): __lowerCamelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str = self.regnet( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states)
652
0
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def snake_case_ (__A : List[Any] , __A : Optional[int] , __A : Dict ) -> tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] __lowerCAmelCase : Union[str, Any] = (low + high) // 2 __lowerCAmelCase : Any = max_subarray(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCAmelCase : Tuple = max_subarray(lowerCamelCase__ , mid + 1 , lowerCamelCase__ ) __lowerCAmelCase : Any = max_cross_sum(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def snake_case_ (__A : Any , __A : int , __A : List[Any] , __A : int ) -> tuple[int, int, float]: __lowerCAmelCase : Dict = float("""-inf""" ), -1 __lowerCAmelCase : Optional[int] = float("""-inf""" ), -1 __lowerCAmelCase : int | float = 0 for i in range(lowerCamelCase__ , low - 1 , -1 ): summ += arr[i] if summ > left_sum: __lowerCAmelCase : Any = summ __lowerCAmelCase : str = i __lowerCAmelCase : Optional[Any] = 0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: __lowerCAmelCase : int = summ __lowerCAmelCase : List[str] = i return max_left, max_right, (left_sum + right_sum) def snake_case_ (__A : Any ) -> float: __lowerCAmelCase : List[str] = [randint(1 , lowerCamelCase__ ) for _ in range(lowerCamelCase__ )] __lowerCAmelCase : Optional[int] = time.time() max_subarray(lowerCamelCase__ , 0 , input_size - 1 ) __lowerCAmelCase : List[Any] = time.time() return end - start def snake_case_ () -> None: __lowerCAmelCase : Optional[int] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] __lowerCAmelCase : Any = [time_max_subarray(lowerCamelCase__ ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(lowerCamelCase__ , lowerCamelCase__ ): print(lowerCamelCase__ , """\t\t""" , lowerCamelCase__ ) plt.plot(lowerCamelCase__ , lowerCamelCase__ ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
651
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels a =object() # For specifying empty leaf dict `{}` a =object() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCamelCase__ ) - len(lowerCamelCase__ ) + 1 ): __lowerCamelCase : str = [x.match(lowerCamelCase__ ) for x, y in zip(lowerCamelCase__ , ks[i:] )] if matches and all(lowerCamelCase__ ): return True return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: def replace(lowerCamelCase__ , lowerCamelCase__ ): for rule, replacement in rules: if _match(lowerCamelCase__ , lowerCamelCase__ ): return replacement return val return replace def SCREAMING_SNAKE_CASE__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , lowerCamelCase__ )), (("transformer", "wte", "embedding"), P('mp' , lowerCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase__ , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCamelCase__ , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = _get_partition_rules() __lowerCamelCase : Optional[Any] = _replacement_rules(lowerCamelCase__ ) __lowerCamelCase : Tuple = {k: _unmatched for k in flatten_dict(lowerCamelCase__ )} __lowerCamelCase : List[Any] = {k: replace(lowerCamelCase__ , lowerCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCamelCase__ ) )
652
0
'''simple docstring''' import argparse import os import re import packaging.version A = '''examples/''' A = { '''examples''': (re.compile(R'''^check_min_version\(\"[^\"]+\"\)\s*$''', re.MULTILINE), '''check_min_version(\"VERSION\")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+\"([^\"]+)\"\s*$''', re.MULTILINE), '''__version__ = \"VERSION\"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*\"[^\"]+\",''', re.MULTILINE), R'''\1version=\"VERSION\",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*\"[^\"]+\"$''', re.MULTILINE), '''release = \"VERSION\"\n'''), } A = { '''init''': '''src/diffusers/__init__.py''', '''setup''': '''setup.py''', } A = '''README.md''' def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[Any]) -> List[Any]: '''simple docstring''' with open(lowerCamelCase__ , 'r' , encoding='utf-8' , newline='\n') as f: _lowercase : Optional[int] = f.read() _lowercase : int = REPLACE_PATTERNS[pattern] _lowercase : str = replace.replace('VERSION' , lowerCamelCase__) _lowercase : List[Any] = re_pattern.sub(lowerCamelCase__ , lowerCamelCase__) with open(lowerCamelCase__ , 'w' , encoding='utf-8' , newline='\n') as f: f.write(lowerCamelCase__) def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Any) -> int: '''simple docstring''' for folder, directories, fnames in os.walk(lowerCamelCase__): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects') if "legacy" in directories: directories.remove('legacy') for fname in fnames: if fname.endswith('.py'): update_version_in_file(os.path.join(lowerCamelCase__ , lowerCamelCase__) , lowerCamelCase__ , pattern='examples') def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any]=False) -> int: '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) if not patch: update_version_in_examples(lowerCamelCase__) def SCREAMING_SNAKE_CASE ( ) -> Tuple: '''simple docstring''' _lowercase : Optional[Any] = '🤗 Transformers currently provides the following architectures' _lowercase : Tuple = '1. Want to contribute a new model?' with open(lowerCamelCase__ , 'r' , encoding='utf-8' , newline='\n') as f: _lowercase : Dict = f.readlines() # Find the start of the list. _lowercase : Union[str, Any] = 0 while not lines[start_index].startswith(_start_prompt): start_index += 1 start_index += 1 _lowercase : List[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt): if lines[index].startswith('1.'): _lowercase : Optional[int] = lines[index].replace( 'https://huggingface.co/docs/diffusers/main/model_doc' , 'https://huggingface.co/docs/diffusers/model_doc' , ) index += 1 with open(lowerCamelCase__ , 'w' , encoding='utf-8' , newline='\n') as f: f.writelines(lowerCamelCase__) def SCREAMING_SNAKE_CASE ( ) -> List[Any]: '''simple docstring''' with open(REPLACE_FILES['init'] , 'r') as f: _lowercase : Optional[Any] = f.read() _lowercase : int = REPLACE_PATTERNS['init'][0].search(lowerCamelCase__).groups()[0] return packaging.version.parse(lowerCamelCase__) def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : str=False) -> Tuple: '''simple docstring''' _lowercase : str = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!') if default_version.is_devrelease: _lowercase : Tuple = default_version.base_version elif patch: _lowercase : Optional[int] = F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: _lowercase : Any = F'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. _lowercase : Optional[Any] = input(F'''Which version are you releasing? [{default_version}]''') if len(lowerCamelCase__) == 0: _lowercase : int = default_version print(F'''Updating version to {version}.''') global_version_update(lowerCamelCase__ , patch=lowerCamelCase__) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: '''simple docstring''' _lowercase : Optional[int] = get_version() _lowercase : Dict = F'''{current_version.major}.{current_version.minor + 1}.0.dev0''' _lowercase : str = current_version.base_version # Check with the user we got that right. _lowercase : List[str] = input(F'''Which version are we developing now? [{dev_version}]''') if len(lowerCamelCase__) == 0: _lowercase : List[Any] = dev_version print(F'''Updating version to {version}.''') global_version_update(lowerCamelCase__) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": A = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') A = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
125
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list: __lowerCamelCase : Union[str, Any] = [True] * n __lowerCamelCase : List[Any] = False __lowerCamelCase : int = False __lowerCamelCase : Any = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __lowerCamelCase : List[str] = i * 2 while index < n: __lowerCamelCase : Optional[int] = False __lowerCamelCase : List[Any] = index + i __lowerCamelCase : Optional[Any] = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 9_9_9_9_6_6_6_6_3_3_3_3 ) -> int: __lowerCamelCase : Optional[Any] = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_0_0 __lowerCamelCase : Dict = prime_sieve(lowerCamelCase__ ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Any = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase : Any = primes[prime_index + 1] __lowerCamelCase : Optional[Any] = last_prime**2 __lowerCamelCase : Dict = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase : Tuple = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase : List[Any] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
652
0
import collections import importlib.util import os import re from pathlib import Path _SCREAMING_SNAKE_CASE = "src/transformers" # Matches is_xxx_available() _SCREAMING_SNAKE_CASE = re.compile(R"is\_([a-z_]*)_available()") # Catches a one-line _import_struct = {xxx} _SCREAMING_SNAKE_CASE = re.compile(R"^_import_structure\s+=\s+\{([^\}]+)\}") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _SCREAMING_SNAKE_CASE = re.compile(R"\s+\"\S*\":\s+\[([^\]]*)\]") # Catches a line if not is_foo_available _SCREAMING_SNAKE_CASE = re.compile(R"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") # Catches a line _import_struct["bla"].append("foo") _SCREAMING_SNAKE_CASE = re.compile(R"^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)") # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _SCREAMING_SNAKE_CASE = re.compile(R"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") # Catches a line with an object between quotes and a comma: "MyModel", _SCREAMING_SNAKE_CASE = re.compile("^\s+\"([^\"]+)\",") # Catches a line with objects between brackets only: ["foo", "bar"], _SCREAMING_SNAKE_CASE = re.compile("^\s+\[([^\]]+)\]") # Catches a line with from foo import bar, bla, boo _SCREAMING_SNAKE_CASE = re.compile(R"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") # Catches a line with try: _SCREAMING_SNAKE_CASE = re.compile(R"^\s*try:") # Catches a line with else: _SCREAMING_SNAKE_CASE = re.compile(R"^\s*else:") def _snake_case (_snake_case : Any) -> Union[str, Any]: if _re_test_backend.search(lowerCamelCase__) is None: return None _lowercase =[b[0] for b in _re_backend.findall(lowerCamelCase__)] backends.sort() return "_and_".join(lowerCamelCase__) def _snake_case (_snake_case : str) -> str: with open(lowerCamelCase__ , 'r' , encoding='utf-8' , newline='\n') as f: _lowercase =f.readlines() _lowercase =0 while line_index < len(lowerCamelCase__) and not lines[line_index].startswith('_import_structure = {'): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowerCamelCase__): return None # First grab the objects without a specific backend in _import_structure _lowercase =[] while not lines[line_index].startswith('if TYPE_CHECKING') and find_backend(lines[line_index]) is None: _lowercase =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowerCamelCase__): _lowercase =_re_one_line_import_struct.search(lowerCamelCase__).groups()[0] _lowercase =re.findall('\[([^\]]+)\]' , lowerCamelCase__) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ')]) line_index += 1 continue _lowercase =_re_import_struct_key_value.search(lowerCamelCase__) if single_line_import_search is not None: _lowercase =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ') if len(lowerCamelCase__) > 0] objects.extend(lowerCamelCase__) elif line.startswith(' ' * 8 + '"'): objects.append(line[9:-3]) line_index += 1 _lowercase ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING'): # If the line is an if not is_backend_available, we grab all objects associated. _lowercase =find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: _lowercase =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 _lowercase =[] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(' ' * 4): _lowercase =lines[line_index] if _re_import_struct_add_one.search(lowerCamelCase__) is not None: objects.append(_re_import_struct_add_one.search(lowerCamelCase__).groups()[0]) elif _re_import_struct_add_many.search(lowerCamelCase__) is not None: _lowercase =_re_import_struct_add_many.search(lowerCamelCase__).groups()[0].split(', ') _lowercase =[obj[1:-1] for obj in imports if len(lowerCamelCase__) > 0] objects.extend(lowerCamelCase__) elif _re_between_brackets.search(lowerCamelCase__) is not None: _lowercase =_re_between_brackets.search(lowerCamelCase__).groups()[0].split(', ') _lowercase =[obj[1:-1] for obj in imports if len(lowerCamelCase__) > 0] objects.extend(lowerCamelCase__) elif _re_quote_object.search(lowerCamelCase__) is not None: objects.append(_re_quote_object.search(lowerCamelCase__).groups()[0]) elif line.startswith(' ' * 8 + '"'): objects.append(line[9:-3]) elif line.startswith(' ' * 12 + '"'): objects.append(line[13:-3]) line_index += 1 _lowercase =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend _lowercase =[] while ( line_index < len(lowerCamelCase__) and find_backend(lines[line_index]) is None and not lines[line_index].startswith('else') ): _lowercase =lines[line_index] _lowercase =_re_import.search(lowerCamelCase__) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ')) elif line.startswith(' ' * 8): objects.append(line[8:-2]) line_index += 1 _lowercase ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowerCamelCase__): # If the line is an if is_backend_available, we grab all objects associated. _lowercase =find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: _lowercase =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 _lowercase =[] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(' ' * 8): _lowercase =lines[line_index] _lowercase =_re_import.search(lowerCamelCase__) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ')) elif line.startswith(' ' * 12): objects.append(line[12:-2]) line_index += 1 _lowercase =objects else: line_index += 1 return import_dict_objects, type_hint_objects def _snake_case (_snake_case : Any , _snake_case : List[Any]) -> Optional[Any]: def find_duplicates(_snake_case : List[Any]): return [k for k, v in collections.Counter(lowerCamelCase__).items() if v > 1] if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): return ["Both sides of the init do not have the same backends!"] _lowercase =[] for key in import_dict_objects.keys(): _lowercase =find_duplicates(import_dict_objects[key]) if duplicate_imports: errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''') _lowercase =find_duplicates(type_hint_objects[key]) if duplicate_type_hints: errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''') if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): _lowercase ='base imports' if key == 'none' else f'''{key} backend''' errors.append(f'''Differences for {name}:''') for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''') for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''') return errors def _snake_case () -> Optional[int]: _lowercase =[] for root, _, files in os.walk(lowerCamelCase__): if "__init__.py" in files: _lowercase =os.path.join(lowerCamelCase__ , '__init__.py') _lowercase =parse_init(lowerCamelCase__) if objects is not None: _lowercase =analyze_results(*lowerCamelCase__) if len(lowerCamelCase__) > 0: _lowercase =f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append('\n'.join(lowerCamelCase__)) if len(lowerCamelCase__) > 0: raise ValueError('\n\n'.join(lowerCamelCase__)) def _snake_case () -> Union[str, Any]: _lowercase =[] for path, directories, files in os.walk(lowerCamelCase__): for folder in directories: # Ignore private modules if folder.startswith('_'): directories.remove(lowerCamelCase__) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowerCamelCase__) / folder).glob('*.py'))) == 0: continue _lowercase =str((Path(lowerCamelCase__) / folder).relative_to(lowerCamelCase__)) _lowercase =short_path.replace(os.path.sep , '.') submodules.append(lowerCamelCase__) for fname in files: if fname == "__init__.py": continue _lowercase =str((Path(lowerCamelCase__) / fname).relative_to(lowerCamelCase__)) _lowercase =short_path.replace('.py' , '').replace(os.path.sep , '.') if len(submodule.split('.')) == 1: submodules.append(lowerCamelCase__) return submodules _SCREAMING_SNAKE_CASE = [ "convert_pytorch_checkpoint_to_tf2", "modeling_flax_pytorch_utils", ] def _snake_case () -> int: # This is to make sure the transformers module imported is the one in the repo. _lowercase =importlib.util.spec_from_file_location( 'transformers' , os.path.join(lowerCamelCase__ , '__init__.py') , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) _lowercase =spec.loader.load_module() _lowercase =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowerCamelCase__) > 0: _lowercase ='\n'.join(f'''- {module}''' for module in module_not_registered) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' f'''{list_of_modules}\n''' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.') if __name__ == "__main__": check_all_inits() check_submodules()
181
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = 1 @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.15 ,SCREAMING_SNAKE_CASE__ : float = 0.01 ,SCREAMING_SNAKE_CASE__ : float = 1348.0 ,SCREAMING_SNAKE_CASE__ : float = 1E-5 ,SCREAMING_SNAKE_CASE__ : int = 1 ,): # standard deviation of the initial noise distribution __lowerCamelCase : int = sigma_max # setable values __lowerCamelCase : List[str] = None self.set_sigmas(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps __lowerCamelCase : Optional[int] = torch.linspace(1 ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,device=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None): __lowerCamelCase : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __lowerCamelCase : Optional[int] = sigma_max if sigma_max is not None else self.config.sigma_max __lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __lowerCamelCase : Optional[Any] = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__) ,math.log(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str]): return torch.where( timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') __lowerCamelCase : List[str] = timestep * torch.ones( sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) __lowerCamelCase : str = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __lowerCamelCase : Dict = timesteps.to(self.discrete_sigmas.device) __lowerCamelCase : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device) __lowerCamelCase : Optional[Any] = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).to(sample.device) __lowerCamelCase : int = torch.zeros_like(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __lowerCamelCase : int = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): __lowerCamelCase : List[Any] = diffusion.unsqueeze(-1) __lowerCamelCase : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __lowerCamelCase : int = randn_tensor( sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__ ,device=sample.device ,dtype=sample.dtype) __lowerCamelCase : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __lowerCamelCase : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,prev_sample_mean=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __lowerCamelCase : Optional[int] = randn_tensor(sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__).to(sample.device) # compute step size from the model_output, the noise, and the snr __lowerCamelCase : str = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __lowerCamelCase : Optional[int] = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): __lowerCamelCase : List[str] = step_size.unsqueeze(-1) __lowerCamelCase : str = sample + step_size * model_output __lowerCamelCase : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,): # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase : int = timesteps.to(original_samples.device) __lowerCamelCase : Any = self.discrete_sigmas.to(original_samples.device)[timesteps] __lowerCamelCase : Optional[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__) * sigmas[:, None, None, None] ) __lowerCamelCase : str = noise + original_samples return noisy_samples def __len__( self : Optional[int]): return self.config.num_train_timesteps
652
0
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch _UpperCamelCase = random.Random() def _a ( _snake_case , _snake_case=1.0 , _snake_case=None , _snake_case=None ): """simple docstring""" if rng is None: UpperCAmelCase = global_rng UpperCAmelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCamelCase__ ( unittest.TestCase ): def __init__( self ,A ,A=7 ,A=400 ,A=2_000 ,A=10 ,A=160 ,A=8 ,A=0.0 ,A=4_000 ,A=False ,A=True ,): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = min_seq_length UpperCAmelCase = max_seq_length UpperCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase = padding_value UpperCAmelCase = sampling_rate UpperCAmelCase = return_attention_mask UpperCAmelCase = do_normalize UpperCAmelCase = feature_size UpperCAmelCase = chunk_length UpperCAmelCase = hop_length def _UpperCamelCase ( self ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self ,A=False ,A=False ): def _flatten(A ): return list(itertools.chain(*SCREAMING_SNAKE_CASE__ ) ) if equal_length: UpperCAmelCase = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCAmelCase = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCamelCase__ ( snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self ): UpperCAmelCase = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase = feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE__ )[0] check_json_file_has_correct_format(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feat_extract_first.to_dict() UpperCAmelCase = feat_extract_second.to_dict() UpperCAmelCase = feat_extract_first.mel_filters UpperCAmelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase = os.path.join(SCREAMING_SNAKE_CASE__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feat_extract_first.to_dict() UpperCAmelCase = feat_extract_second.to_dict() UpperCAmelCase = feat_extract_first.mel_filters UpperCAmelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs] # Test feature size UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,padding="""max_length""" ,return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input UpperCAmelCase = feature_extractor(speech_inputs[0] ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ).input_features self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test batched UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCAmelCase = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCAmelCase = np.asarray(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test truncation required UpperCAmelCase = [floats_list((1, x) )[0] for x in range(200 ,(feature_extractor.n_samples + 500) ,200 )] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs] UpperCAmelCase = [x[: feature_extractor.n_samples] for x in speech_inputs] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs_truncated] UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) def _UpperCamelCase ( self ): import torch UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = np.random.rand(100 ,32 ).astype(np.floataa ) UpperCAmelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCAmelCase = feature_extractor.pad([{"""input_features""": inputs}] ,return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCAmelCase = feature_extractor.pad([{"""input_features""": inputs}] ,return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self ,A ): UpperCAmelCase = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech UpperCAmelCase = ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE__ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self ): # fmt: off UpperCAmelCase = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on UpperCAmelCase = self._load_datasamples(1 ) UpperCAmelCase = WhisperFeatureExtractor() UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape ,(1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] ,SCREAMING_SNAKE_CASE__ ,atol=1e-4 ) ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = self._load_datasamples(1 )[0] UpperCAmelCase = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue UpperCAmelCase = feat_extract.zero_mean_unit_var_norm([audio] ,attention_mask=SCREAMING_SNAKE_CASE__ )[0] self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE__ ) - 1 ) < 1e-3 ) )
341
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> str: '''simple docstring''' snake_case : Optional[int] = [] for line in lines: snake_case : Optional[Any] = re.sub(R'''#.*''' , '''''' , lowerCamelCase__ ) # remove comments if line: filtered_lines.append(lowerCamelCase__ ) snake_case : int = '\n'.join(lowerCamelCase__ ) # Make a hash from all this code snake_case : Tuple = full_str.encode('''utf-8''' ) return shaaaa(lowerCamelCase__ ).hexdigest() # get importable module names and hash for caching lowercase__ = { "csv": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), "json": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), "pandas": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), "parquet": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), "arrow": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), "text": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), "imagefolder": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), "audiofolder": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions lowercase__ = { ".csv": ("csv", {}), ".tsv": ("csv", {"sep": "\t"}), ".json": ("json", {}), ".jsonl": ("json", {}), ".parquet": ("parquet", {}), ".arrow": ("arrow", {}), ".txt": ("text", {}), } _EXTENSION_TO_MODULE.update({ext: ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) lowercase__ = {"imagefolder", "audiofolder"} # Used to filter data files based on extensions given a module name lowercase__ = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(".zip") _MODULE_TO_EXTENSIONS["audiofolder"].append(".zip")
638
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : Optional[int] = [file for file in files if n_ not in file] else: __lowerCamelCase : Dict = [file for file in files if n_identifier not in file] __lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : Optional[int] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : int = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = 'modeling' __lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = Path('src/transformers') __lowerCamelCase : Optional[int] = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : str = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = Path('docs/source') __lowerCamelCase : str = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
652
0
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class __lowercase ( a_ ): """simple docstring""" UpperCamelCase : Union[List[PIL.Image.Image], np.ndarray] UpperCamelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
457
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} a ={ """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } a ={"""vinai/bartpho-syllable""": 1024} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Any="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="<s>" ,SCREAMING_SNAKE_CASE__ : int="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<mask>" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = vocab_file __lowerCamelCase : Tuple = monolingual_vocab_file __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__)) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Any = cnt cnt += 1 with open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for line in f.readlines(): __lowerCamelCase : Any = line.strip().split()[0] __lowerCamelCase : List[str] = len(self.fairseq_tokens_to_ids) if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Dict = len(self.fairseq_tokens_to_ids) __lowerCamelCase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): __lowerCamelCase : Tuple = self.__dict__.copy() __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : str = {} __lowerCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Tuple = [self.cls_token_id] __lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Dict = [self.sep_token_id] __lowerCamelCase : 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 lowerCAmelCase ( self : List[str]): return len(self.fairseq_ids_to_tokens) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): return self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Any = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( SCREAMING_SNAKE_CASE__) and os.path.isfile(self.monolingual_vocab_file): copyfile(self.monolingual_vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.monolingual_vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(SCREAMING_SNAKE_CASE__)} \n") return out_vocab_file, out_monolingual_vocab_file
652
0
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES _a : Dict = logging.get_logger(__name__) _a : Optional[int] = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) _a : Optional[Any] = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) _a : Union[str, Any] = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) _a : Optional[int] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) _a : Optional[int] = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) _a : List[Any] = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) _a : Tuple = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) _a : Dict = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) _a : Union[str, Any] = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) _a : Any = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) _a : Optional[Any] = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) _a : List[str] = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) _a : List[Any] = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) _a : Optional[Any] = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) _a : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) _a : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) _a : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) _a : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) _a : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) _a : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) _a : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) _a : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) _a : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) _a : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) _a : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) _a : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) _a : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) _a : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : Dict =FLAX_MODEL_MAPPING _a : Optional[int] = auto_class_update(FlaxAutoModel) class _UpperCAmelCase ( _BaseAutoModelClass ): a : int =FLAX_MODEL_FOR_PRETRAINING_MAPPING _a : List[str] = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : str =FLAX_MODEL_FOR_CAUSAL_LM_MAPPING _a : Union[str, Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : List[str] =FLAX_MODEL_FOR_MASKED_LM_MAPPING _a : List[str] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : int =FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _a : Tuple = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : str =FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _a : Any = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : Optional[Any] =FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING _a : List[str] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : Dict =FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING _a : Union[str, Any] = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : Optional[Any] =FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING _a : List[Any] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : Tuple =FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING _a : Optional[Any] = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : Optional[Any] =FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _a : Union[str, Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class _UpperCAmelCase ( _BaseAutoModelClass ): a : str =FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING _a : int = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class _UpperCAmelCase ( _BaseAutoModelClass ): a : int =FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING _a : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
689
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_3 ,SCREAMING_SNAKE_CASE__ : int=3_0 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=3_2 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2 ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Dict = image_size __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = is_training __lowerCamelCase : List[Any] = use_labels __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : List[str] = scope __lowerCamelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCamelCase : str = (image_size // patch_size) ** 2 __lowerCamelCase : str = num_patches + 2 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : List[Any] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any]): return DeiTConfig( 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=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Optional[Any] = TFDeiTModel(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCamelCase : int = 1 __lowerCamelCase : Tuple = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.type_sequence_label_size __lowerCamelCase : List[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = config_and_inputs __lowerCamelCase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _UpperCAmelCase : List[Any] = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = TFDeiTModelTester(self) __lowerCamelCase : Optional[int] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : str): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,tf.keras.layers.Dense)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Any = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=False): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224') __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : Tuple = prepare_img() __lowerCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='tf') # forward pass __lowerCamelCase : int = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tf.constant([-1.0266, 0.1912, -1.2861]) self.assertTrue(np.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
652
0
import string def _lowercase ( __SCREAMING_SNAKE_CASE ) -> None: for key in range(len(string.ascii_uppercase ) ): UpperCamelCase__ : List[Any] = '' for symbol in message: if symbol in string.ascii_uppercase: UpperCamelCase__ : Any = string.ascii_uppercase.find(lowerCamelCase__ ) UpperCamelCase__ : int = num - key if num < 0: UpperCamelCase__ : Tuple = num + len(string.ascii_uppercase ) UpperCamelCase__ : Optional[Any] = translated + string.ascii_uppercase[num] else: UpperCamelCase__ : Union[str, Any] = translated + symbol print(F"""Decryption using Key #{key}: {translated}""" ) def _lowercase ( ) -> None: UpperCamelCase__ : Tuple = input('Encrypted message: ' ) UpperCamelCase__ : Tuple = message.upper() decrypt(lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
410
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] _UpperCAmelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
652
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowerCAmelCase__ ( lowerCamelCase : List[Any]=None ): _A : Tuple = argparse.ArgumentParser(add_help=lowerCamelCase__ ,allow_abbrev=lowerCamelCase__ ) # The main config parser _A : List[Any] = config_command_parser(lowerCamelCase__ ) # The subparser to add commands to _A : List[Any] = config_parser.add_subparsers(title='subcommands' ,dest='subcommand' ) # Then add other parsers with the parent parser default_command_parser(lowerCamelCase__ ,parents=[parent_parser] ) update_command_parser(lowerCamelCase__ ,parents=[parent_parser] ) return config_parser def lowerCAmelCase__ ( ): _A : int = get_config_parser() _A : Any = config_parser.parse_args() if not hasattr(lowerCamelCase__ ,'func' ): config_parser.print_help() exit(1 ) # Run args.func(lowerCamelCase__ ) if __name__ == "__main__": main()
128
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
652
0
"""simple docstring""" import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def a_ ( __a , __a , __a ): # Construct model if openai_config_file == "": A__ = OpenAIGPTConfig() else: A__ = OpenAIGPTConfig.from_json_file(lowerCamelCase__ ) A__ = OpenAIGPTModel(lowerCamelCase__ ) # Load weights from numpy load_tf_weights_in_openai_gpt(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model A__ = pytorch_dump_folder_path + '/' + WEIGHTS_NAME A__ = pytorch_dump_folder_path + '/' + CONFIG_NAME print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() , lowerCamelCase__ ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(lowerCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __snake_case : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--openai_checkpoint_folder_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--openai_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __snake_case : str = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
571
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """vocab.txt"""} a ={ """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } a ={ """openbmb/cpm-ant-10b""": 1024, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: __lowerCamelCase : int = collections.OrderedDict() with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as reader: __lowerCamelCase : Optional[int] = reader.readlines() for index, token in enumerate(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = token.rstrip('\n' ) __lowerCamelCase : Union[str, Any] = index return vocab class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[int]="<unk>" ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_0): __lowerCamelCase : str = vocab __lowerCamelCase : Dict = unk_token __lowerCamelCase : int = max_input_chars_per_word def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > self.max_input_chars_per_word: return [self.unk_token] __lowerCamelCase : Tuple = 0 __lowerCamelCase : str = [] while start < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = None while start < end: __lowerCamelCase : Any = ''.join(chars[start:end]) if substr in self.vocab: __lowerCamelCase : Optional[Any] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = end return sub_tokens class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = ['''input_ids''', '''attention_mask'''] _UpperCAmelCase : Optional[int] = False def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple="<d>" ,SCREAMING_SNAKE_CASE__ : Tuple="</d>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="</s>" ,SCREAMING_SNAKE_CASE__ : str="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<unk>" ,SCREAMING_SNAKE_CASE__ : List[Any]="</n>" ,SCREAMING_SNAKE_CASE__ : int="</_>" ,SCREAMING_SNAKE_CASE__ : List[Any]="left" ,**SCREAMING_SNAKE_CASE__ : List[str] ,): requires_backends(self ,['jieba']) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ ,eod_token=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,line_token=SCREAMING_SNAKE_CASE__ ,space_token=SCREAMING_SNAKE_CASE__ ,padding_side=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Optional[Any] = bod_token __lowerCamelCase : Dict = eod_token __lowerCamelCase : Any = load_vocab(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.encoder[space_token] __lowerCamelCase : Dict = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __lowerCamelCase : Optional[Any] = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) __lowerCamelCase : int = {v: k for k, v in self.encoder.items()} __lowerCamelCase : Union[str, Any] = WordpieceTokenizer(vocab=self.encoder ,unk_token=self.unk_token) @property def lowerCAmelCase ( self : List[Any]): return self.encoder[self.bod_token] @property def lowerCAmelCase ( self : Tuple): return self.encoder[self.eod_token] @property def lowerCAmelCase ( self : Union[str, Any]): return self.encoder["\n"] @property def lowerCAmelCase ( self : str): return len(self.encoder) def lowerCAmelCase ( self : str): return dict(self.encoder ,**self.added_tokens_encoder) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Any = [] for x in jieba.cut(SCREAMING_SNAKE_CASE__ ,cut_all=SCREAMING_SNAKE_CASE__): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__)) return output_tokens def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Tuple = [i for i in token_ids if i >= 0] __lowerCamelCase : str = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[Any]): return token in self.encoder def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.encoder.get(SCREAMING_SNAKE_CASE__ ,self.encoder.get(self.unk_token)) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.decoder.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : int = (filename_prefix + '-' if filename_prefix else '') + save_directory __lowerCamelCase : Any = 0 if " " in self.encoder: __lowerCamelCase : Any = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: __lowerCamelCase : str = self.encoder['\n'] del self.encoder["\n"] __lowerCamelCase : str = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Any = token_index writer.write(token + '\n') index += 1 return (vocab_file,) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : List[int] = None): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__))
652
0
'''simple docstring''' from collections.abc import Sequence def UpperCamelCase ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict = False ): if not arr: return 0 A__ = 0 if allow_empty_subarrays else float("-inf" ) A__ = 0.0 for num in arr: A__ = max(0 if allow_empty_subarrays else num , curr_sum + num ) A__ = max(lowerCamelCase__ , lowerCamelCase__ ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() __lowerCAmelCase : Dict =[-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
440
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a ={"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
652
0
import functools def snake_case_ (__A : Optional[Any] , __A : int ) -> int: # Validation if not isinstance(lowerCamelCase__ , lowerCamelCase__ ) or not all(isinstance(lowerCamelCase__ , lowerCamelCase__ ) for day in days ): raise ValueError("""The parameter days should be a list of integers""" ) if len(lowerCamelCase__ ) != 3 or not all(isinstance(lowerCamelCase__ , lowerCamelCase__ ) for cost in costs ): raise ValueError("""The parameter costs should be a list of three integers""" ) if len(lowerCamelCase__ ) == 0: return 0 if min(lowerCamelCase__ ) <= 0: raise ValueError("""All days elements should be greater than 0""" ) if max(lowerCamelCase__ ) >= 3_6_6: raise ValueError("""All days elements should be less than 366""" ) __lowerCAmelCase : List[Any] = set(lowerCamelCase__ ) @functools.cache def dynamic_programming(__A : List[str] ) -> int: if index > 3_6_5: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 3_0 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
651
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = (UnCLIPScheduler,) def lowerCAmelCase ( self : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Any = { 'num_train_timesteps': 1_0_0_0, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**SCREAMING_SNAKE_CASE__) return config def lowerCAmelCase ( self : Optional[Any]): for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any]): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): for clip_sample_range in [1, 5, 1_0, 2_0]: self.check_over_configs(clip_sample_range=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any]): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): for time_step in [0, 5_0_0, 9_9_9]: for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Any = self.get_scheduler_config(variance_type='fixed_small_log') __lowerCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE__) assert torch.sum(torch.abs(scheduler._get_variance(0) - 1.00_00E-10)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7) - 0.0549625)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9) - 0.9994987)) < 1E-5 def lowerCAmelCase ( self : Any): __lowerCamelCase : Dict = self.scheduler_classes[0] __lowerCamelCase : List[str] = self.get_scheduler_config(variance_type='learned_range') __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = 0.5 assert scheduler._get_variance(1 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -10.1712790 < 1E-5 assert scheduler._get_variance(4_8_7 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -5.7998052 < 1E-5 assert scheduler._get_variance(9_9_9 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -0.0010011 < 1E-5 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : str = self.get_scheduler_config() __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = scheduler.timesteps __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter __lowerCamelCase : List[str] = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : int = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # 2. predict previous mean of sample x_t-1 __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Optional[Any] = pred_prev_sample __lowerCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 252.2682495) < 1E-2 assert abs(result_mean.item() - 0.3284743) < 1E-3 def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : List[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(2_5) __lowerCamelCase : int = scheduler.timesteps __lowerCamelCase : Tuple = self.dummy_model() __lowerCamelCase : Any = self.dummy_sample_deter __lowerCamelCase : Any = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if i + 1 == timesteps.shape[0]: __lowerCamelCase : Optional[Any] = None else: __lowerCamelCase : Union[str, Any] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __lowerCamelCase : int = scheduler.step( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Union[str, Any] = pred_prev_sample __lowerCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 258.2044983) < 1E-2 assert abs(result_mean.item() - 0.3362038) < 1E-3 def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Union[str, Any]): pass
652
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available A = {'''tokenization_herbert''': ['''HerbertTokenizer''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['''HerbertTokenizerFast'''] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
125
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''swin2sr''' _UpperCAmelCase : Any = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=1 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : Tuple=1_8_0 ,SCREAMING_SNAKE_CASE__ : Any=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : int=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=8 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2.0 ,SCREAMING_SNAKE_CASE__ : Optional[int]=True ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-5 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Tuple=1.0 ,SCREAMING_SNAKE_CASE__ : int="1conv" ,SCREAMING_SNAKE_CASE__ : Optional[int]="pixelshuffle" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = image_size __lowerCamelCase : str = patch_size __lowerCamelCase : List[Any] = num_channels __lowerCamelCase : Dict = embed_dim __lowerCamelCase : Dict = depths __lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = num_heads __lowerCamelCase : Tuple = window_size __lowerCamelCase : Dict = mlp_ratio __lowerCamelCase : str = qkv_bias __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[Any] = attention_probs_dropout_prob __lowerCamelCase : List[Any] = drop_path_rate __lowerCamelCase : Optional[int] = hidden_act __lowerCamelCase : Dict = use_absolute_embeddings __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : str = initializer_range __lowerCamelCase : List[Any] = upscale __lowerCamelCase : List[Any] = img_range __lowerCamelCase : List[str] = resi_connection __lowerCamelCase : Union[str, Any] = upsampler
652
0
def _snake_case (_snake_case : Union[str, Any]) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__): raise TypeError('only integers accepted as input') else: _lowercase =str(abs(lowerCamelCase__)) _lowercase =[list(lowerCamelCase__) for char in range(len(lowerCamelCase__))] for index in range(len(lowerCamelCase__)): num_transpositions[index].pop(lowerCamelCase__) return max( int(''.join(list(lowerCamelCase__))) for transposition in num_transpositions) if __name__ == "__main__": __import__("doctest").testmod()
181
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__="pt" ) -> Dict: __lowerCamelCase : Any = {'add_prefix_space': True} if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not line.startswith(' ' ) else {} __lowerCamelCase : int = padding_side return tokenizer( [line] , max_length=lowerCamelCase__ , padding='max_length' if pad_to_max_length else None , truncation=lowerCamelCase__ , return_tensors=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , ) -> List[str]: __lowerCamelCase : List[str] = input_ids.ne(lowerCamelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]="train" ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[Any]="" ,): super().__init__() __lowerCamelCase : Optional[Any] = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.source') __lowerCamelCase : Any = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.target') __lowerCamelCase : List[Any] = self.get_char_lens(self.src_file) __lowerCamelCase : List[Any] = max_source_length __lowerCamelCase : List[str] = max_target_length assert min(self.src_lens) > 0, F"found empty line in {self.src_file}" __lowerCamelCase : Any = tokenizer __lowerCamelCase : Optional[int] = prefix if n_obs is not None: __lowerCamelCase : Dict = self.src_lens[:n_obs] __lowerCamelCase : str = src_lang __lowerCamelCase : Any = tgt_lang def __len__( self : Tuple): return len(self.src_lens) def __getitem__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Dict = index + 1 # linecache starts at 1 __lowerCamelCase : Any = self.prefix + linecache.getline(str(self.src_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') __lowerCamelCase : int = linecache.getline(str(self.tgt_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __lowerCamelCase : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer ) __lowerCamelCase : Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer __lowerCamelCase : List[str] = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_source_length ,'right') __lowerCamelCase : Any = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_target_length ,'right') __lowerCamelCase : List[Any] = source_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = target_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : int): return [len(SCREAMING_SNAKE_CASE__) for x in Path(SCREAMING_SNAKE_CASE__).open().readlines()] def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[Any] = torch.stack([x['input_ids'] for x in batch]) __lowerCamelCase : Any = torch.stack([x['attention_mask'] for x in batch]) __lowerCamelCase : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch]) __lowerCamelCase : Optional[int] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch a =getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return list(itertools.chain.from_iterable(lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: __lowerCamelCase : str = get_git_info() save_json(lowerCamelCase__ , os.path.join(lowerCamelCase__ , 'git_log.json' ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=4 , **lowerCamelCase__ ) -> List[str]: with open(lowerCamelCase__ , 'w' ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=lowerCamelCase__ , **lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: with open(lowerCamelCase__ ) as f: return json.load(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: __lowerCamelCase : str = git.Repo(search_parent_directories=lowerCamelCase__ ) __lowerCamelCase : Any = { 'repo_id': str(lowerCamelCase__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List: return list(map(lowerCamelCase__ , lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: with open(lowerCamelCase__ , 'wb' ) as f: return pickle.dump(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: def remove_articles(lowerCamelCase__ ): return re.sub(R'\b(a|an|the)\b' , ' ' , lowerCamelCase__ ) def white_space_fix(lowerCamelCase__ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase__ ): __lowerCamelCase : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : str = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Optional[int] = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) & Counter(lowerCamelCase__ ) __lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 __lowerCamelCase : List[Any] = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : int = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: return normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) __lowerCamelCase : Dict = 0 for hypo, pred in zip(lowerCamelCase__ , lowerCamelCase__ ): em += exact_match_score(lowerCamelCase__ , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: em /= len(lowerCamelCase__ ) return {"em": em} def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return model_prefix.startswith('rag' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __lowerCamelCase : List[str] = 'dropout_rate' for p in extra_params: if getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if not hasattr(lowerCamelCase__ , lowerCamelCase__ ) and not hasattr(lowerCamelCase__ , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) continue __lowerCamelCase : List[Any] = p if hasattr(lowerCamelCase__ , lowerCamelCase__ ) else equivalent_param[p] setattr(lowerCamelCase__ , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) return hparams, config
652
0
"""simple docstring""" def _a ( _snake_case , _snake_case ): """simple docstring""" if number < 0 or shift_amount < 0: raise ValueError("""both inputs must be positive integers""" ) UpperCAmelCase = str(bin(lowerCamelCase__ ) ) binary_number += "0" * shift_amount return binary_number def _a ( _snake_case , _snake_case ): """simple docstring""" if number < 0 or shift_amount < 0: raise ValueError("""both inputs must be positive integers""" ) UpperCAmelCase = str(bin(lowerCamelCase__ ) )[2:] if shift_amount >= len(lowerCamelCase__ ): return "0b0" UpperCAmelCase = binary_number[: len(lowerCamelCase__ ) - shift_amount] return "0b" + shifted_binary_number def _a ( _snake_case , _snake_case ): """simple docstring""" if number >= 0: # Get binary representation of positive number UpperCAmelCase = '0' + str(bin(lowerCamelCase__ ) ).strip("""-""" )[2:] else: # Get binary (2's complement) representation of negative number UpperCAmelCase = len(bin(lowerCamelCase__ )[3:] ) # Find 2's complement of number UpperCAmelCase = bin(abs(lowerCamelCase__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase = ( '1' + '0' * (binary_number_length - len(lowerCamelCase__ )) + binary_number ) if shift_amount >= len(lowerCamelCase__ ): return "0b" + binary_number[0] * len(lowerCamelCase__ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(lowerCamelCase__ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
341
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a =logging.get_logger(__name__) # General docstring a ="""MobileNetV1Config""" # Base docstring a ="""google/mobilenet_v1_1.0_224""" a =[1, 1024, 7, 7] # Image classification docstring a ="""google/mobilenet_v1_1.0_224""" a ="""tabby, tabby cat""" a =[ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> str: __lowerCamelCase : str = {} if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = model.mobilenet_va else: __lowerCamelCase : List[str] = model __lowerCamelCase : List[Any] = 'MobilenetV1/Conv2d_0/' __lowerCamelCase : List[Any] = backbone.conv_stem.convolution.weight __lowerCamelCase : List[str] = backbone.conv_stem.normalization.bias __lowerCamelCase : Tuple = backbone.conv_stem.normalization.weight __lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean __lowerCamelCase : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(1_3 ): __lowerCamelCase : Any = i + 1 __lowerCamelCase : Union[str, Any] = i * 2 __lowerCamelCase : Optional[Any] = backbone.layer[pt_index] __lowerCamelCase : Optional[int] = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" __lowerCamelCase : Tuple = pointer.convolution.weight __lowerCamelCase : Optional[Any] = pointer.normalization.bias __lowerCamelCase : Union[str, Any] = pointer.normalization.weight __lowerCamelCase : List[str] = pointer.normalization.running_mean __lowerCamelCase : Union[str, Any] = pointer.normalization.running_var __lowerCamelCase : int = backbone.layer[pt_index + 1] __lowerCamelCase : Union[str, Any] = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" __lowerCamelCase : Optional[Any] = pointer.convolution.weight __lowerCamelCase : Any = pointer.normalization.bias __lowerCamelCase : str = pointer.normalization.weight __lowerCamelCase : Dict = pointer.normalization.running_mean __lowerCamelCase : List[str] = pointer.normalization.running_var if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __lowerCamelCase : Any = model.classifier.weight __lowerCamelCase : int = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __lowerCamelCase : List[str] = tf.train.list_variables(lowerCamelCase__ ) __lowerCamelCase : List[str] = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) __lowerCamelCase : Any = tf.train.load_variable(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[Any] = array # Build TF to PyTorch weights loading map __lowerCamelCase : Tuple = _build_tf_to_pytorch_map(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue __lowerCamelCase : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __lowerCamelCase : List[str] = np.transpose(lowerCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __lowerCamelCase : Any = array.squeeze().transpose() else: __lowerCamelCase : Tuple = np.transpose(lowerCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) __lowerCamelCase : Optional[Any] = torch.from_numpy(lowerCamelCase__ ) tf_weights.pop(lowerCamelCase__ , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp' , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp_1' , lowerCamelCase__ ) tf_weights.pop(name + '/ExponentialMovingAverage' , lowerCamelCase__ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: __lowerCamelCase , __lowerCamelCase : int = features.shape[-2:] __lowerCamelCase , __lowerCamelCase : List[str] = conv_layer.stride __lowerCamelCase , __lowerCamelCase : str = conv_layer.kernel_size if in_height % stride_height == 0: __lowerCamelCase : Optional[int] = max(kernel_height - stride_height , 0 ) else: __lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __lowerCamelCase : List[str] = max(kernel_width - stride_width , 0 ) else: __lowerCamelCase : List[str] = max(kernel_width - (in_width % stride_width) , 0 ) __lowerCamelCase : List[str] = pad_along_width // 2 __lowerCamelCase : Optional[int] = pad_along_width - pad_left __lowerCamelCase : Any = pad_along_height // 2 __lowerCamelCase : List[Any] = pad_along_height - pad_top __lowerCamelCase : Union[str, Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(lowerCamelCase__ , lowerCamelCase__ , 'constant' , 0.0 ) class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[bool or str] = True ,): super().__init__() __lowerCamelCase : Dict = config if in_channels % groups != 0: raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups.") if out_channels % groups != 0: raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups.") __lowerCamelCase : Optional[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2) __lowerCamelCase : Optional[int] = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__ ,padding_mode='zeros' ,) if use_normalization: __lowerCamelCase : Optional[int] = nn.BatchNormad( num_features=SCREAMING_SNAKE_CASE__ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=SCREAMING_SNAKE_CASE__ ,track_running_stats=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Dict = None if use_activation: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = ACTaFN[use_activation] elif isinstance(config.hidden_act ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = ACTaFN[config.hidden_act] else: __lowerCamelCase : List[str] = config.hidden_act else: __lowerCamelCase : List[str] = None def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): if self.config.tf_padding: __lowerCamelCase : Any = apply_tf_padding(SCREAMING_SNAKE_CASE__ ,self.convolution) __lowerCamelCase : Optional[int] = self.convolution(SCREAMING_SNAKE_CASE__) if self.normalization is not None: __lowerCamelCase : Dict = self.normalization(SCREAMING_SNAKE_CASE__) if self.activation is not None: __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return features class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = MobileNetVaConfig _UpperCAmelCase : List[str] = load_tf_weights_in_mobilenet_va _UpperCAmelCase : List[str] = '''mobilenet_v1''' _UpperCAmelCase : Any = '''pixel_values''' _UpperCAmelCase : int = False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[nn.Linear, nn.Convad]): if isinstance(SCREAMING_SNAKE_CASE__ ,(nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ ,nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : bool = True): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = config __lowerCamelCase : Optional[int] = 3_2 __lowerCamelCase : List[str] = max(int(depth * config.depth_multiplier) ,config.min_depth) __lowerCamelCase : Optional[Any] = MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=config.num_channels ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=2 ,) __lowerCamelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __lowerCamelCase : str = nn.ModuleList() for i in range(1_3): __lowerCamelCase : str = out_channels if strides[i] == 2 or i == 0: depth *= 2 __lowerCamelCase : str = max(int(depth * config.depth_multiplier) ,config.min_depth) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=strides[i] ,groups=SCREAMING_SNAKE_CASE__ ,)) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,)) __lowerCamelCase : Optional[int] = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') __lowerCamelCase : Optional[Any] = self.conv_stem(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Any = all_hidden_states + (hidden_states,) __lowerCamelCase : Optional[Any] = hidden_states if self.pooler is not None: __lowerCamelCase : Tuple = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__) ,start_dim=1) else: __lowerCamelCase : List[str] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = config.num_labels __lowerCamelCase : Optional[Any] = MobileNetVaModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __lowerCamelCase : Any = nn.Dropout(config.classifier_dropout_prob ,inplace=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Optional[int] = self.mobilenet_va(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] = self.classifier(self.dropout(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : int = 'single_label_classification' else: __lowerCamelCase : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : Tuple = MSELoss() if self.num_labels == 1: __lowerCamelCase : int = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : Union[str, Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : List[str] = CrossEntropyLoss() __lowerCamelCase : List[str] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : int = BCEWithLogitsLoss() __lowerCamelCase : int = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states ,)
652
0
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> list: '''simple docstring''' snake_case : Tuple = [0] * len(lowerCamelCase__ ) for i in range(1 , len(lowerCamelCase__ ) ): # use last results for better performance - dynamic programming snake_case : Optional[Any] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: snake_case : Optional[Any] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 snake_case : int = j return prefix_result def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> int: '''simple docstring''' return max(prefix_function(lowerCamelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod()
638
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = cva.getAffineTransform(lowerCamelCase__ , lowerCamelCase__ ) return cva.warpAffine(lowerCamelCase__ , lowerCamelCase__ , (rows, cols) ) if __name__ == "__main__": # read original image a =cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value a =cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a , a =gray_img.shape # set different points to rotate image a =np.array([[50, 50], [200, 50], [50, 200]], np.floataa) a =np.array([[10, 100], [200, 50], [100, 250]], np.floataa) a =np.array([[50, 50], [150, 50], [120, 200]], np.floataa) a =np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list a =[ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a =plt.figure(1) a =["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
652
0
def __lowerCamelCase ( lowerCamelCase__ : Tuple , lowerCamelCase__ : List[str] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : Any ): '''simple docstring''' if index == r: for j in range(lowerCamelCase__ ): print(data[j] , end=""" """ ) print(""" """ ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location lowerCamelCase = arr[i] combination_util(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , index + 1 , lowerCamelCase__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def __lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int] ): '''simple docstring''' lowerCamelCase = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , 0 , lowerCamelCase__ , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCAmelCase : int = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
457
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : List[str] = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCamelCase__ ) if number < 1: __lowerCamelCase : int = F"Input value of [number={number}] must be > 0" raise ValueError(lowerCamelCase__ ) elif number == 1: return 3 elif number == 2: return 5 else: __lowerCamelCase : Any = int(math.log(number // 3 , 2 ) ) + 2 __lowerCamelCase : List[Any] = [3, 5] __lowerCamelCase : Union[str, Any] = 2 __lowerCamelCase : List[str] = 3 for block in range(1 , lowerCamelCase__ ): for _ in range(lowerCamelCase__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): a =0 try: a =proth(number) except ValueError: print(F"""ValueError: there is no {number}th Proth number""") continue print(F"""The {number}th Proth number: {value}""")
652
0
'''simple docstring''' from collections.abc import Sequence def _lowerCAmelCase ( lowercase = None ) -> int: if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) __lowerCAmelCase = nums[0] for i in range(1 , len(lowerCamelCase__ ) ): __lowerCAmelCase = nums[i] __lowerCAmelCase = max(lowerCamelCase__ , ans + num , lowerCamelCase__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _a : int = int(input("""Enter number of elements : """).strip()) _a : str = list(map(int, input("""\nEnter the numbers : """).strip().split()))[:n] print(max_subsequence_sum(array))
689
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class A_ ( unittest.TestCase ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=7 ,SCREAMING_SNAKE_CASE__ : Any=3 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0 ,SCREAMING_SNAKE_CASE__ : int=4_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[str]=1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : Tuple=True ,): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCamelCase : List[Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} __lowerCamelCase : str = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : int = num_channels __lowerCamelCase : Dict = min_resolution __lowerCamelCase : Tuple = max_resolution __lowerCamelCase : Dict = do_resize __lowerCamelCase : List[Any] = size __lowerCamelCase : Tuple = do_normalize __lowerCamelCase : Any = image_mean __lowerCamelCase : List[str] = image_std __lowerCamelCase : List[Any] = do_rescale __lowerCamelCase : str = rescale_factor __lowerCamelCase : Tuple = do_pad def lowerCAmelCase ( self : Dict): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=False): if not batched: __lowerCamelCase : Optional[Any] = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ ,Image.Image): __lowerCamelCase , __lowerCamelCase : Any = image.size else: __lowerCamelCase , __lowerCamelCase : Any = image.shape[1], image.shape[2] if w < h: __lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w) __lowerCamelCase : Tuple = self.size['shortest_edge'] elif w > h: __lowerCamelCase : Union[str, Any] = self.size['shortest_edge'] __lowerCamelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h) else: __lowerCamelCase : List[Any] = self.size['shortest_edge'] __lowerCamelCase : Optional[int] = self.size['shortest_edge'] else: __lowerCamelCase : List[str] = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase : List[Any] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) __lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[0])[0] __lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[1])[1] return expected_height, expected_width @require_torch @require_vision class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[int] = DetaImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = DetaImageProcessingTester(self) @property def lowerCAmelCase ( self : Any): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_std')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_rescale')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_pad')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'size')) def lowerCAmelCase ( self : str): __lowerCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size ,{'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}) self.assertEqual(image_processor.do_pad ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): pass def lowerCAmelCase ( self : List[str]): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random PIL images __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,Image.Image) # Test not batched input __lowerCamelCase : List[Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : str): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,np.ndarray) # Test not batched input __lowerCamelCase : Tuple = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : int): # Initialize image_processing __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,torch.Tensor) # Test not batched input __lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) @slow def lowerCAmelCase ( self : Optional[Any]): # prepare image and target __lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r') as f: __lowerCamelCase : List[str] = json.loads(f.read()) __lowerCamelCase : Union[str, Any] = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them __lowerCamelCase : Optional[int] = DetaImageProcessor() __lowerCamelCase : int = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Dict = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : int = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : Tuple = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : List[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify orig_size __lowerCamelCase : str = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : int = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__)) @slow def lowerCAmelCase ( self : str): # prepare image, target and masks_path __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r') as f: __lowerCamelCase : Tuple = json.loads(f.read()) __lowerCamelCase : List[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} __lowerCamelCase : Optional[int] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them __lowerCamelCase : List[str] = DetaImageProcessor(format='coco_panoptic') __lowerCamelCase : Optional[Any] = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,masks_path=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : Tuple = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : int = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : int = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify masks __lowerCamelCase : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,SCREAMING_SNAKE_CASE__) # verify orig_size __lowerCamelCase : Any = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : Any = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
652
0
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase__ : str = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = { '''Visual-Attention-Network/van-base''': ( '''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json''' ), } class UpperCamelCase_ ( __UpperCamelCase ): '''simple docstring''' UpperCamelCase_ = '''van''' def __init__( self , UpperCamelCase=2_24 , UpperCamelCase=3 , UpperCamelCase=[7, 3, 3, 3] , UpperCamelCase=[4, 2, 2, 2] , UpperCamelCase=[64, 1_28, 3_20, 5_12] , UpperCamelCase=[3, 3, 12, 3] , UpperCamelCase=[8, 8, 4, 4] , UpperCamelCase="gelu" , UpperCamelCase=0.02 , UpperCamelCase=1E-6 , UpperCamelCase=1E-2 , UpperCamelCase=0.0 , UpperCamelCase=0.0 , **UpperCamelCase , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__) UpperCamelCase__ : Any = image_size UpperCamelCase__ : Optional[Any] = num_channels UpperCamelCase__ : List[str] = patch_sizes UpperCamelCase__ : Union[str, Any] = strides UpperCamelCase__ : Tuple = hidden_sizes UpperCamelCase__ : Any = depths UpperCamelCase__ : Tuple = mlp_ratios UpperCamelCase__ : Dict = hidden_act UpperCamelCase__ : Tuple = initializer_range UpperCamelCase__ : List[str] = layer_norm_eps UpperCamelCase__ : Optional[Any] = layer_scale_init_value UpperCamelCase__ : Dict = drop_path_rate UpperCamelCase__ : List[str] = dropout_rate
410
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_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[Any] = KandinskyVaaControlnetPipeline _UpperCAmelCase : Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : int = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : List[Any] = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _UpperCAmelCase : Tuple = False @property def lowerCAmelCase ( self : Tuple): return 3_2 @property def lowerCAmelCase ( self : List[Any]): return 3_2 @property def lowerCAmelCase ( self : str): return self.time_input_dim @property def lowerCAmelCase ( self : List[str]): return self.time_input_dim * 4 @property def lowerCAmelCase ( self : List[str]): return 1_0_0 @property def lowerCAmelCase ( self : Dict): torch.manual_seed(0) __lowerCamelCase : 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, } __lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__) return model @property def lowerCAmelCase ( self : Union[str, Any]): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Optional[Any]): torch.manual_seed(0) __lowerCamelCase : int = VQModel(**self.dummy_movq_kwargs) return model def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = self.dummy_unet __lowerCamelCase : List[Any] = self.dummy_movq __lowerCamelCase : str = DDIMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='linear' ,beta_start=0.00085 ,beta_end=0.012 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Dict = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=0): __lowerCamelCase : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1)).to( SCREAMING_SNAKE_CASE__) # create hint __lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) if str(SCREAMING_SNAKE_CASE__).startswith('mps'): __lowerCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 6_4, 'width': 6_4, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = 'cpu' __lowerCamelCase : Tuple = self.get_dummy_components() __lowerCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = output.images __lowerCamelCase : Tuple = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) ,return_dict=SCREAMING_SNAKE_CASE__ ,)[0] __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : List[str] = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]) assert ( np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : int): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy') __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png') __lowerCamelCase : Tuple = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 255.0 __lowerCamelCase : str = hint.permute(2 ,0 ,1).unsqueeze(0) __lowerCamelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa) pipe_prior.to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' ,torch_dtype=torch.floataa) __lowerCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE__) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 'A robot, 4k photo' __lowerCamelCase : List[str] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe_prior( SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple() __lowerCamelCase : Optional[Any] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase : Any = pipeline( image_embeds=SCREAMING_SNAKE_CASE__ ,negative_image_embeds=SCREAMING_SNAKE_CASE__ ,hint=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
652
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING A : Union[str, Any] = logging.get_logger(__name__) class __lowerCamelCase ( a_ ): """simple docstring""" a = '''upernet''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE : List[Any]=None , SCREAMING_SNAKE_CASE : Optional[Any]=512 , SCREAMING_SNAKE_CASE : Tuple=0.02 , SCREAMING_SNAKE_CASE : Union[str, Any]=[1, 2, 3, 6] , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : str=0.4 , SCREAMING_SNAKE_CASE : str=384 , SCREAMING_SNAKE_CASE : Tuple=256 , SCREAMING_SNAKE_CASE : Dict=1 , SCREAMING_SNAKE_CASE : Any=False , SCREAMING_SNAKE_CASE : Union[str, Any]=255 , **SCREAMING_SNAKE_CASE : Tuple , ): super().__init__(**SCREAMING_SNAKE_CASE__) if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.') _A : int = CONFIG_MAPPING['resnet'](out_features=['stage1', 'stage2', 'stage3', 'stage4']) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): _A : List[Any] = backbone_config.get('model_type') _A : Optional[Any] = CONFIG_MAPPING[backbone_model_type] _A : List[Any] = config_class.from_dict(SCREAMING_SNAKE_CASE__) _A : List[str] = backbone_config _A : List[Any] = hidden_size _A : Optional[int] = initializer_range _A : Dict = pool_scales _A : Optional[int] = use_auxiliary_head _A : Optional[Any] = auxiliary_loss_weight _A : Any = auxiliary_in_channels _A : Tuple = auxiliary_channels _A : Optional[int] = auxiliary_num_convs _A : str = auxiliary_concat_input _A : int = loss_ignore_index def A ( self : List[Any]): _A : str = copy.deepcopy(self.__dict__) _A : Optional[Any] = self.backbone_config.to_dict() _A : List[Any] = self.__class__.model_type return output
128
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : _UpperCAmelCase : int = XGLMConfig _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Tuple = '''gelu''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 ,SCREAMING_SNAKE_CASE__ : Tuple=7 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=9_9 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : Tuple=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,): __lowerCamelCase : List[str] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_input_mask __lowerCamelCase : str = use_labels __lowerCamelCase : Any = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : List[str] = ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : Tuple = activation_dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Any = None __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 2 __lowerCamelCase : Dict = 1 def lowerCAmelCase ( self : Any): return XGLMConfig.from_pretrained('facebook/xglm-564M') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) ,clip_value_min=0 ,clip_value_max=3) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : int = self.get_config() __lowerCamelCase : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[Any]): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=SCREAMING_SNAKE_CASE__ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : int): __lowerCamelCase : int = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : str = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : str = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _UpperCAmelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else () _UpperCAmelCase : str = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Tuple = TFXGLMModelTester(self) __lowerCamelCase : int = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,n_embd=3_7) def lowerCAmelCase ( self : List[Any]): self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : str): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.') def lowerCAmelCase ( self : Union[str, Any]): super().test_resize_token_embeddings() @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True): __lowerCamelCase : Any = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]] ,dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __lowerCamelCase : Optional[Any] = [2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1] # fmt: on __lowerCamelCase : int = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') tf.random.set_seed(0) __lowerCamelCase : Optional[Any] = tokenizer('Today is a nice day and' ,return_tensors='tf') __lowerCamelCase : List[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0'): __lowerCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,seed=[7, 0]) __lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = 'left' # use different length sentences to test batching __lowerCamelCase : List[str] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __lowerCamelCase : List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='tf' ,padding=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['input_ids'] __lowerCamelCase : Dict = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=inputs['attention_mask'] ,max_new_tokens=1_2) __lowerCamelCase : Tuple = tokenizer(sentences[0] ,return_tensors='tf').input_ids __lowerCamelCase : List[str] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : Any = tokenizer(sentences[1] ,return_tensors='tf').input_ids __lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tokenizer.decode(output_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[non_padded_sentence, padded_sentence])
652
0
"""simple docstring""" import operator as op def a_ ( __a ): A__ = [] A__ = lambda __a , __a : int(x / y ) # noqa: E731 integer division operation A__ = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('''Symbol'''.center(8 ) , '''Action'''.center(12 ) , '''Stack''' , sep=''' | ''' ) print('''-''' * (30 + len(lowerCamelCase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(lowerCamelCase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('''push(''' + x + ''')''').ljust(12 ) , ''','''.join(lowerCamelCase__ ) , sep=''' | ''' ) else: A__ = stack.pop() # pop stack # output in tabular format print(''''''.rjust(8 ) , ('''pop(''' + b + ''')''').ljust(12 ) , ''','''.join(lowerCamelCase__ ) , sep=''' | ''' ) A__ = stack.pop() # pop stack # output in tabular format print(''''''.rjust(8 ) , ('''pop(''' + a + ''')''').ljust(12 ) , ''','''.join(lowerCamelCase__ ) , sep=''' | ''' ) stack.append( str(opr[x](int(lowerCamelCase__ ) , int(lowerCamelCase__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('''push(''' + a + x + b + ''')''').ljust(12 ) , ''','''.join(lowerCamelCase__ ) , sep=''' | ''' , ) return int(stack[0] ) if __name__ == "__main__": __snake_case : Dict = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ') print('\n\tResult = ', solve(Postfix))
571
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
652
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class UpperCAmelCase ( unittest.TestCase ): def UpperCAmelCase_ ( self :List[Any] )-> str: A__ = tempfile.mkdtemp() # fmt: off A__ = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on A__ = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) A__ = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] A__ = {'unk_token': '<unk>'} A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) ) A__ = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } A__ = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Union[str, Any] , **lowercase_ :Optional[Any] )-> int: return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Dict , **lowercase_ :str )-> str: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Optional[int] , **lowercase_ :str )-> str: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Optional[Any] )-> List[str]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self :int )-> Tuple: A__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A__ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self :int )-> Tuple: A__ = self.get_tokenizer() A__ = self.get_rust_tokenizer() A__ = self.get_image_processor() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) A__ = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) A__ = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Dict )-> Tuple: A__ = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A__ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) A__ = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A__ = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :str )-> Dict: A__ = self.get_image_processor() A__ = self.get_tokenizer() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) A__ = self.prepare_image_inputs() A__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) A__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ ( self :Any )-> Union[str, Any]: A__ = self.get_image_processor() A__ = self.get_tokenizer() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) A__ = 'lower newer' A__ = processor(text=SCREAMING_SNAKE_CASE__ ) A__ = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self :Union[str, Any] )-> List[str]: A__ = self.get_image_processor() A__ = self.get_tokenizer() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) A__ = 'lower newer' A__ = self.prepare_image_inputs() A__ = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def UpperCAmelCase_ ( self :Tuple )-> Union[str, Any]: A__ = self.get_image_processor() A__ = self.get_tokenizer() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) A__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A__ = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) A__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase_ ( self :Tuple )-> Dict: A__ = self.get_image_processor() A__ = self.get_tokenizer() A__ = CLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) A__ = 'lower newer' A__ = self.prepare_image_inputs() A__ = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
440
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a =logging.get_logger(__name__) # General docstring a ="""RegNetConfig""" # Base docstring a ="""facebook/regnet-y-040""" a =[1, 1088, 7, 7] # Image classification docstring a ="""facebook/regnet-y-040""" a ="""tabby, tabby cat""" a =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : Optional[str] = "relu" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2) __lowerCamelCase : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,strides=SCREAMING_SNAKE_CASE__ ,padding='VALID' ,groups=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution' ,) __lowerCamelCase : int = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') __lowerCamelCase : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Dict): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = config.num_channels __lowerCamelCase : Dict = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='embedder' ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__)[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,strides=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution') __lowerCamelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False): return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__) ,training=SCREAMING_SNAKE_CASE__) class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') __lowerCamelCase : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='relu' ,name='attention.0'), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='sigmoid' ,name='attention.2'), ] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__) for layer_module in self.attention: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = hidden_state * pooled return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[Any]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = max(1 ,out_channels // config.groups_width) __lowerCamelCase : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.2'), ] __lowerCamelCase : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : int = hidden_state for layer_module in self.layers: __lowerCamelCase : List[str] = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : int = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1 __lowerCamelCase : Tuple = max(1 ,out_channels // config.groups_width) __lowerCamelCase : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ ,reduced_channels=int(round(in_channels / 4)) ,name='layer.2'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.3'), ] __lowerCamelCase : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[int] = hidden_state for layer_module in self.layers: __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : Any = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCamelCase : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='layers.0'), *[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,name=F"layers.{i+1}") for i in range(depth - 1)], ] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): for layer_module in self.layers: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='stages.0' ,)) __lowerCamelCase : Optional[int] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:])): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__ ,name=F"stages.{i+1}")) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Optional[Any] = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__) @keras_serializable class A_ ( tf.keras.layers.Layer ): _UpperCAmelCase : List[Any] = RegNetConfig def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = config __lowerCamelCase : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ ,name='embedder') __lowerCamelCase : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ ,name='encoder') __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') @unpack_inputs def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,): __lowerCamelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = encoder_outputs[0] __lowerCamelCase : int = self.pooler(SCREAMING_SNAKE_CASE__) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) __lowerCamelCase : str = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) for h in encoder_outputs[1]]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : Optional[int] = '''regnet''' _UpperCAmelCase : List[Any] = '''pixel_values''' @property def lowerCAmelCase ( self : int): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) ,dtype=tf.floataa)} a =r""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : int=False ,): __lowerCamelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__ ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : str): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = config.num_labels __lowerCamelCase : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') # classification head __lowerCamelCase : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='classifier.1') if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Any=False ,): __lowerCamelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str = self.regnet( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states)
652
0
import math import unittest def snake_case_ (__A : int ) -> bool: assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: """simple docstring""" self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: """simple docstring""" with self.assertRaises(SCREAMING_SNAKE_CASE__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , """Zero doesn\'t have any positive factors, primes must have exactly two.""" , ) self.assertFalse( is_prime(1 ) , """One only has 1 positive factor, primes must have exactly two.""" , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
651
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels a =object() # For specifying empty leaf dict `{}` a =object() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCamelCase__ ) - len(lowerCamelCase__ ) + 1 ): __lowerCamelCase : str = [x.match(lowerCamelCase__ ) for x, y in zip(lowerCamelCase__ , ks[i:] )] if matches and all(lowerCamelCase__ ): return True return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: def replace(lowerCamelCase__ , lowerCamelCase__ ): for rule, replacement in rules: if _match(lowerCamelCase__ , lowerCamelCase__ ): return replacement return val return replace def SCREAMING_SNAKE_CASE__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , lowerCamelCase__ )), (("transformer", "wte", "embedding"), P('mp' , lowerCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase__ , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCamelCase__ , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = _get_partition_rules() __lowerCamelCase : Optional[Any] = _replacement_rules(lowerCamelCase__ ) __lowerCamelCase : Tuple = {k: _unmatched for k in flatten_dict(lowerCamelCase__ )} __lowerCamelCase : List[Any] = {k: replace(lowerCamelCase__ , lowerCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCamelCase__ ) )
652
0
'''simple docstring''' import datasets from .evaluate import evaluate A = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' A = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' A = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _lowerCamelCase ( self : Any ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': { 'id': datasets.Value('string' ), 'prediction_text': datasets.features.Sequence(datasets.Value('string' ) ), }, 'references': { 'id': datasets.Value('string' ), 'answers': datasets.features.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), }, } ) ,codebase_urls=['https://www.atticusprojectai.org/cuad'] ,reference_urls=['https://www.atticusprojectai.org/cuad'] ,) def _lowerCamelCase ( self : Optional[int] ,UpperCamelCase : List[str] ,UpperCamelCase : Tuple ) -> int: _lowercase : Dict = {prediction['id']: prediction['prediction_text'] for prediction in predictions} _lowercase : List[str] = [ { 'paragraphs': [ { 'qas': [ { 'answers': [{'text': answer_text} for answer_text in ref['answers']['text']], 'id': ref['id'], } for ref in references ] } ] } ] _lowercase : str = evaluate(dataset=SCREAMING_SNAKE_CASE__ ,predictions=SCREAMING_SNAKE_CASE__ ) return score
125
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list: __lowerCamelCase : Union[str, Any] = [True] * n __lowerCamelCase : List[Any] = False __lowerCamelCase : int = False __lowerCamelCase : Any = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __lowerCamelCase : List[str] = i * 2 while index < n: __lowerCamelCase : Optional[int] = False __lowerCamelCase : List[Any] = index + i __lowerCamelCase : Optional[Any] = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 9_9_9_9_6_6_6_6_3_3_3_3 ) -> int: __lowerCamelCase : Optional[Any] = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_0_0 __lowerCamelCase : Dict = prime_sieve(lowerCamelCase__ ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Any = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase : Any = primes[prime_index + 1] __lowerCamelCase : Optional[Any] = last_prime**2 __lowerCamelCase : Dict = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase : Tuple = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase : List[Any] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
652
0
_SCREAMING_SNAKE_CASE = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _SCREAMING_SNAKE_CASE = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _snake_case (_snake_case : List[Any] , _snake_case : Tuple , _snake_case : Union[str, Any]) -> list[int]: _lowercase =True _lowercase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) order.append(lowerCamelCase__) return order def _snake_case (_snake_case : Any , _snake_case : List[str] , _snake_case : Tuple) -> list[int]: _lowercase =True _lowercase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) return component def _snake_case (_snake_case : List[str]) -> list[list[int]]: _lowercase =len(lowerCamelCase__) * [False] _lowercase ={vert: [] for vert in range(len(lowerCamelCase__))} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(lowerCamelCase__) _lowercase =[] for i, was_visited in enumerate(lowerCamelCase__): if not was_visited: order += topology_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) _lowercase =[] _lowercase =len(lowerCamelCase__) * [False] for i in range(len(lowerCamelCase__)): _lowercase =order[len(lowerCamelCase__) - i - 1] if not visited[vert]: _lowercase =find_components(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) components_list.append(lowerCamelCase__) return components_list
181
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = 1 @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.15 ,SCREAMING_SNAKE_CASE__ : float = 0.01 ,SCREAMING_SNAKE_CASE__ : float = 1348.0 ,SCREAMING_SNAKE_CASE__ : float = 1E-5 ,SCREAMING_SNAKE_CASE__ : int = 1 ,): # standard deviation of the initial noise distribution __lowerCamelCase : int = sigma_max # setable values __lowerCamelCase : List[str] = None self.set_sigmas(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps __lowerCamelCase : Optional[int] = torch.linspace(1 ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,device=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None): __lowerCamelCase : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __lowerCamelCase : Optional[int] = sigma_max if sigma_max is not None else self.config.sigma_max __lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __lowerCamelCase : Optional[Any] = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__) ,math.log(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str]): return torch.where( timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') __lowerCamelCase : List[str] = timestep * torch.ones( sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) __lowerCamelCase : str = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __lowerCamelCase : Dict = timesteps.to(self.discrete_sigmas.device) __lowerCamelCase : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device) __lowerCamelCase : Optional[Any] = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).to(sample.device) __lowerCamelCase : int = torch.zeros_like(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __lowerCamelCase : int = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): __lowerCamelCase : List[Any] = diffusion.unsqueeze(-1) __lowerCamelCase : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __lowerCamelCase : int = randn_tensor( sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__ ,device=sample.device ,dtype=sample.dtype) __lowerCamelCase : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __lowerCamelCase : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,prev_sample_mean=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __lowerCamelCase : Optional[int] = randn_tensor(sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__).to(sample.device) # compute step size from the model_output, the noise, and the snr __lowerCamelCase : str = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __lowerCamelCase : Optional[int] = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): __lowerCamelCase : List[str] = step_size.unsqueeze(-1) __lowerCamelCase : str = sample + step_size * model_output __lowerCamelCase : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,): # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase : int = timesteps.to(original_samples.device) __lowerCamelCase : Any = self.discrete_sigmas.to(original_samples.device)[timesteps] __lowerCamelCase : Optional[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__) * sigmas[:, None, None, None] ) __lowerCamelCase : str = noise + original_samples return noisy_samples def __len__( self : Optional[int]): return self.config.num_train_timesteps
652
0
"""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, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase__ ( snake_case , snake_case , snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = StableDiffusionInstructPixaPixPipeline SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS def _UpperCamelCase ( self ): torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=8 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=32 ,) UpperCAmelCase = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__ ) torch.manual_seed(0 ) UpperCAmelCase = 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 ,) torch.manual_seed(0 ) UpperCAmelCase = 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 ,) UpperCAmelCase = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _UpperCamelCase ( self ,A ,A=0 ): UpperCAmelCase = floats_tensor((1, 3, 32, 32) ,rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = image.cpu().permute(0 ,2 ,3 ,1 )[0] UpperCAmelCase = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__ ) ).convert("""RGB""" ) if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): UpperCAmelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: UpperCAmelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def _UpperCamelCase ( self ): UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = 'french fries' UpperCAmelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ,negative_prompt=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = output.images UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = [inputs['prompt']] * 2 UpperCAmelCase = np.array(inputs["""image"""] ).astype(np.floataa ) / 255.0 UpperCAmelCase = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ).to(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = image / 2 + 0.5 UpperCAmelCase = image.permute(0 ,3 ,1 ,2 ) UpperCAmelCase = image.repeat(2 ,1 ,1 ,1 ) UpperCAmelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) UpperCAmelCase = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = EulerAncestralDiscreteScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ) UpperCAmelCase = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[0, -3:, -3:, -1] UpperCAmelCase = [round(SCREAMING_SNAKE_CASE__ ,4 ) for x in image_slice.flatten().tolist()] print(""",""".join([str(SCREAMING_SNAKE_CASE__ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) UpperCAmelCase = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def _UpperCamelCase ( self ): UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = StableDiffusionInstructPixaPixPipeline(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = VaeImageProcessor(do_resize=SCREAMING_SNAKE_CASE__ ,do_normalize=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = pipe(**self.get_dummy_inputs_by_type(SCREAMING_SNAKE_CASE__ ,input_image_type="""pt""" ) )[0] UpperCAmelCase = components['vae'] UpperCAmelCase = self.get_dummy_inputs_by_type(SCREAMING_SNAKE_CASE__ ,input_image_type="""pt""" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): UpperCAmelCase = vae.encode(inputs[image_param] ).latent_dist.mode() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ )[0] UpperCAmelCase = np.abs(out - out_latents_inputs ).max() self.assertLess(SCREAMING_SNAKE_CASE__ ,1e-4 ,"""passing latents as image input generate different result from passing image""" ) @slow @require_torch_gpu class lowerCamelCase__ ( unittest.TestCase ): def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase ( self ,A=0 ): UpperCAmelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = load_image( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" ) UpperCAmelCase = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def _UpperCamelCase ( self ): UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" ,safety_checker=SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() UpperCAmelCase = self.get_inputs() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" ,safety_checker=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() UpperCAmelCase = self.get_inputs() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" ,safety_checker=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() UpperCAmelCase = self.get_inputs() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ ).images UpperCAmelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) UpperCAmelCase = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _UpperCamelCase ( self ): UpperCAmelCase = 0 def callback_fn(A ,A ,A ) -> None: UpperCAmelCase = True nonlocal number_of_steps number_of_steps += 1 if step == 1: UpperCAmelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) UpperCAmelCase = latents[0, -3:, -3:, -1] UpperCAmelCase = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: UpperCAmelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) UpperCAmelCase = latents[0, -3:, -3:, -1] UpperCAmelCase = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 UpperCAmelCase = False UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" ,safety_checker=SCREAMING_SNAKE_CASE__ ,torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() UpperCAmelCase = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE__ ,callback=SCREAMING_SNAKE_CASE__ ,callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _UpperCamelCase ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" ,safety_checker=SCREAMING_SNAKE_CASE__ ,torch_dtype=torch.floataa ) UpperCAmelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCAmelCase = self.get_inputs() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def _UpperCamelCase ( self ): UpperCAmelCase = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 UpperCAmelCase = inputs['image'].resize((504, 504) ) UpperCAmelCase = 'timbrooks/instruct-pix2pix' UpperCAmelCase = StableDiffusionInstructPixaPixPipeline.from_pretrained( SCREAMING_SNAKE_CASE__ ,safety_checker=SCREAMING_SNAKE_CASE__ ,) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() UpperCAmelCase = pipe(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = output.images[0] UpperCAmelCase = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) UpperCAmelCase = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
341
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' import math def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> float: '''simple docstring''' if ( not isinstance(lowerCamelCase__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * power_factor def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> float: '''simple docstring''' if ( not isinstance(lowerCamelCase__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
638
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : Optional[int] = [file for file in files if n_ not in file] else: __lowerCamelCase : Dict = [file for file in files if n_identifier not in file] __lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : Optional[int] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : int = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = 'modeling' __lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = Path('src/transformers') __lowerCamelCase : Optional[int] = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : str = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = Path('docs/source') __lowerCamelCase : str = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
652
0
from jiwer import compute_measures import datasets UpperCAmelCase : List[str] = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" UpperCAmelCase : Dict = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n" UpperCAmelCase : int = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowercase ( datasets.Metric ): """simple docstring""" def __A ( self ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def __A ( self , A=None , A=None , A=False ) -> List[str]: '''simple docstring''' if concatenate_texts: return compute_measures(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )["wer"] else: lowerCamelCase = 0 lowerCamelCase = 0 for prediction, reference in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCamelCase = compute_measures(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
457
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} a ={ """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } a ={"""vinai/bartpho-syllable""": 1024} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Any="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="<s>" ,SCREAMING_SNAKE_CASE__ : int="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<mask>" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = vocab_file __lowerCamelCase : Tuple = monolingual_vocab_file __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__)) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Any = cnt cnt += 1 with open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for line in f.readlines(): __lowerCamelCase : Any = line.strip().split()[0] __lowerCamelCase : List[str] = len(self.fairseq_tokens_to_ids) if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Dict = len(self.fairseq_tokens_to_ids) __lowerCamelCase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): __lowerCamelCase : Tuple = self.__dict__.copy() __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : str = {} __lowerCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Tuple = [self.cls_token_id] __lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Dict = [self.sep_token_id] __lowerCamelCase : 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 lowerCAmelCase ( self : List[str]): return len(self.fairseq_ids_to_tokens) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): return self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Any = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( SCREAMING_SNAKE_CASE__) and os.path.isfile(self.monolingual_vocab_file): copyfile(self.monolingual_vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.monolingual_vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(SCREAMING_SNAKE_CASE__)} \n") return out_vocab_file, out_monolingual_vocab_file
652
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar _a : Tuple = TypeVar("""T""") class _UpperCAmelCase ( Generic[T] ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = None __lowerCAmelCase = len(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = [any_type for _ in range(self.N )] + arr __lowerCAmelCase = fnc self.build() def lowerCamelCase__ ( self ): '''simple docstring''' for p in range(self.N - 1,0,-1 ): __lowerCAmelCase = self.fn(self.st[p * 2],self.st[p * 2 + 1] ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' p += self.N __lowerCAmelCase = v while p > 1: __lowerCAmelCase = p // 2 __lowerCAmelCase = self.fn(self.st[p * 2],self.st[p * 2 + 1] ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): # noqa: E741 '''simple docstring''' __lowerCAmelCase = l + self.N, r + self.N __lowerCAmelCase = None while l <= r: if l % 2 == 1: __lowerCAmelCase = self.st[l] if res is None else self.fn(SCREAMING_SNAKE_CASE__,self.st[l] ) if r % 2 == 0: __lowerCAmelCase = self.st[r] if res is None else self.fn(SCREAMING_SNAKE_CASE__,self.st[r] ) __lowerCAmelCase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce _a : Optional[int] = [1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] _a : Union[str, Any] = { 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } _a : Optional[Any] = SegmentTree(test_array, min) _a : Union[str, Any] = SegmentTree(test_array, max) _a : str = SegmentTree(test_array, lambda a, b: a + b) def _lowerCAmelCase ( ) -> None: for i in range(len(lowerCamelCase__ ) ): for j in range(lowerCamelCase__ , len(lowerCamelCase__ ) ): __lowerCAmelCase = reduce(lowerCamelCase__ , test_array[i : j + 1] ) __lowerCAmelCase = reduce(lowerCamelCase__ , test_array[i : j + 1] ) __lowerCAmelCase = reduce(lambda lowercase , lowercase : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(lowerCamelCase__ , lowerCamelCase__ ) assert max_range == max_segment_tree.query(lowerCamelCase__ , lowerCamelCase__ ) assert sum_range == sum_segment_tree.query(lowerCamelCase__ , lowerCamelCase__ ) test_all_segments() for index, value in test_updates.items(): _a : int = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
689
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_3 ,SCREAMING_SNAKE_CASE__ : int=3_0 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=3_2 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2 ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Dict = image_size __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = is_training __lowerCamelCase : List[Any] = use_labels __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : List[str] = scope __lowerCamelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCamelCase : str = (image_size // patch_size) ** 2 __lowerCamelCase : str = num_patches + 2 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : List[Any] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any]): return DeiTConfig( 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=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Optional[Any] = TFDeiTModel(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCamelCase : int = 1 __lowerCamelCase : Tuple = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.type_sequence_label_size __lowerCamelCase : List[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = config_and_inputs __lowerCamelCase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _UpperCAmelCase : List[Any] = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = TFDeiTModelTester(self) __lowerCamelCase : Optional[int] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : str): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,tf.keras.layers.Dense)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Any = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=False): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224') __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : Tuple = prepare_img() __lowerCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='tf') # forward pass __lowerCamelCase : int = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tf.constant([-1.0266, 0.1912, -1.2861]) self.assertTrue(np.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
652
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase_ : '''simple docstring''' @staticmethod def lowerCAmelCase__ ( *UpperCamelCase , **UpperCamelCase) -> str: pass @is_pipeline_test @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def lowerCAmelCase__ ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase) -> List[Any]: UpperCamelCase__ : Optional[Any] = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa') UpperCamelCase__ : List[str] = [ { 'image': Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'), 'question': 'How many cats are there?', }, { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'question': 'How many cats are there?', }, ] return vqa_pipeline, examples def lowerCAmelCase__ ( self , UpperCamelCase , UpperCamelCase) -> Optional[Any]: UpperCamelCase__ : int = vqa_pipeline(SCREAMING_SNAKE_CASE__ , top_k=1) self.assertEqual( SCREAMING_SNAKE_CASE__ , [ [{'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}], [{'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}], ] , ) @require_torch def lowerCAmelCase__ ( self) -> int: UpperCamelCase__ : Tuple = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa') UpperCamelCase__ : Tuple = './tests/fixtures/tests_samples/COCO/000000039769.png' UpperCamelCase__ : Optional[Any] = 'How many cats are there?' UpperCamelCase__ : Tuple = vqa_pipeline(image=SCREAMING_SNAKE_CASE__ , question='How many cats are there?' , top_k=2) self.assertEqual( SCREAMING_SNAKE_CASE__ , [{'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}, {'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}]) UpperCamelCase__ : Union[str, Any] = vqa_pipeline({'image': image, 'question': question} , top_k=2) self.assertEqual( SCREAMING_SNAKE_CASE__ , [{'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}, {'score': ANY(SCREAMING_SNAKE_CASE__), 'answer': ANY(SCREAMING_SNAKE_CASE__)}]) @slow @require_torch def lowerCAmelCase__ ( self) -> List[Any]: UpperCamelCase__ : int = pipeline('visual-question-answering' , model='dandelin/vilt-b32-finetuned-vqa') UpperCamelCase__ : Dict = './tests/fixtures/tests_samples/COCO/000000039769.png' UpperCamelCase__ : Optional[int] = 'How many cats are there?' UpperCamelCase__ : Tuple = vqa_pipeline(image=SCREAMING_SNAKE_CASE__ , question=SCREAMING_SNAKE_CASE__ , top_k=2) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]) UpperCamelCase__ : int = vqa_pipeline({'image': image, 'question': question} , top_k=2) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]) UpperCamelCase__ : Optional[int] = vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ , decimals=4) , [[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2 , ) @require_tf @unittest.skip('Visual question answering not implemented in TF') def lowerCAmelCase__ ( self) -> Union[str, Any]: pass
410
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] _UpperCAmelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
652
0
'''simple docstring''' import itertools import math def lowerCAmelCase__ ( lowerCamelCase : Tuple ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(math.sqrt(lowerCamelCase__ ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase__ ( ): _A : Union[str, Any] = 2 while True: if is_prime(lowerCamelCase__ ): yield num num += 1 def lowerCAmelCase__ ( lowerCamelCase : List[str] = 10001 ): return next(itertools.islice(prime_generator() ,nth - 1 ,lowerCamelCase__ ) ) if __name__ == "__main__": print(f"""{solution() = }""")
128
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
652
0
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand __snake_case : str = logging.get_logger(__name__) # pylint: disable=invalid-name def a_ ( __a ): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(lowerCamelCase__ ): return ext raise Exception( f'''Unable to determine file format from file extension {path}. ''' f'''Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}''' ) def a_ ( __a ): A__ = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) A__ = try_infer_format_from_ext(args.input ) if args.format == 'infer' else args.format A__ = PipelineDataFormat.from_str( format=lowerCamelCase__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(lowerCamelCase__ , lowerCamelCase__ ) class UpperCamelCase ( a ): """simple docstring""" def __init__( self : Tuple , _lowerCamelCase : Pipeline , _lowerCamelCase : PipelineDataFormat ): A__ = nlp A__ = reader @staticmethod def A__ ( _lowerCamelCase : ArgumentParser ): A__ = parser.add_parser('''run''' , help='''Run a pipeline through the CLI''' ) run_parser.add_argument('''--task''' , choices=get_supported_tasks() , help='''Task to run''' ) run_parser.add_argument('''--input''' , type=SCREAMING_SNAKE_CASE__ , help='''Path to the file to use for inference''' ) run_parser.add_argument('''--output''' , type=SCREAMING_SNAKE_CASE__ , help='''Path to the file that will be used post to write results.''' ) run_parser.add_argument('''--model''' , type=SCREAMING_SNAKE_CASE__ , help='''Name or path to the model to instantiate.''' ) run_parser.add_argument('''--config''' , type=SCREAMING_SNAKE_CASE__ , help='''Name or path to the model\'s config to instantiate.''' ) run_parser.add_argument( '''--tokenizer''' , type=SCREAMING_SNAKE_CASE__ , help='''Name of the tokenizer to use. (default: same as the model name)''' ) run_parser.add_argument( '''--column''' , type=SCREAMING_SNAKE_CASE__ , help='''Name of the column to use as input. (For multi columns input as QA use column1,columns2)''' , ) run_parser.add_argument( '''--format''' , type=SCREAMING_SNAKE_CASE__ , default='''infer''' , choices=PipelineDataFormat.SUPPORTED_FORMATS , help='''Input format to read from''' , ) run_parser.add_argument( '''--device''' , type=SCREAMING_SNAKE_CASE__ , default=-1 , help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)''' , ) run_parser.add_argument('''--overwrite''' , action='''store_true''' , help='''Allow overwriting the output file.''' ) run_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def A__ ( self : Union[str, Any] ): A__ = self._nlp, [] for entry in self._reader: A__ = nlp(**SCREAMING_SNAKE_CASE__ ) if self._reader.is_multi_columns else nlp(SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): outputs.append(SCREAMING_SNAKE_CASE__ ) else: outputs += output # Saving data if self._nlp.binary_output: A__ = self._reader.save_binary(SCREAMING_SNAKE_CASE__ ) logger.warning(F'''Current pipeline requires output to be in binary format, saving at {binary_path}''' ) else: self._reader.save(SCREAMING_SNAKE_CASE__ )
571
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """vocab.txt"""} a ={ """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } a ={ """openbmb/cpm-ant-10b""": 1024, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: __lowerCamelCase : int = collections.OrderedDict() with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as reader: __lowerCamelCase : Optional[int] = reader.readlines() for index, token in enumerate(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = token.rstrip('\n' ) __lowerCamelCase : Union[str, Any] = index return vocab class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[int]="<unk>" ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_0): __lowerCamelCase : str = vocab __lowerCamelCase : Dict = unk_token __lowerCamelCase : int = max_input_chars_per_word def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > self.max_input_chars_per_word: return [self.unk_token] __lowerCamelCase : Tuple = 0 __lowerCamelCase : str = [] while start < len(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = None while start < end: __lowerCamelCase : Any = ''.join(chars[start:end]) if substr in self.vocab: __lowerCamelCase : Optional[Any] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = end return sub_tokens class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = ['''input_ids''', '''attention_mask'''] _UpperCAmelCase : Optional[int] = False def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple="<d>" ,SCREAMING_SNAKE_CASE__ : Tuple="</d>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="</s>" ,SCREAMING_SNAKE_CASE__ : str="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<unk>" ,SCREAMING_SNAKE_CASE__ : List[Any]="</n>" ,SCREAMING_SNAKE_CASE__ : int="</_>" ,SCREAMING_SNAKE_CASE__ : List[Any]="left" ,**SCREAMING_SNAKE_CASE__ : List[str] ,): requires_backends(self ,['jieba']) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ ,eod_token=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,line_token=SCREAMING_SNAKE_CASE__ ,space_token=SCREAMING_SNAKE_CASE__ ,padding_side=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Optional[Any] = bod_token __lowerCamelCase : Dict = eod_token __lowerCamelCase : Any = load_vocab(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.encoder[space_token] __lowerCamelCase : Dict = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __lowerCamelCase : Optional[Any] = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) __lowerCamelCase : int = {v: k for k, v in self.encoder.items()} __lowerCamelCase : Union[str, Any] = WordpieceTokenizer(vocab=self.encoder ,unk_token=self.unk_token) @property def lowerCAmelCase ( self : List[Any]): return self.encoder[self.bod_token] @property def lowerCAmelCase ( self : Tuple): return self.encoder[self.eod_token] @property def lowerCAmelCase ( self : Union[str, Any]): return self.encoder["\n"] @property def lowerCAmelCase ( self : str): return len(self.encoder) def lowerCAmelCase ( self : str): return dict(self.encoder ,**self.added_tokens_encoder) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Any = [] for x in jieba.cut(SCREAMING_SNAKE_CASE__ ,cut_all=SCREAMING_SNAKE_CASE__): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__)) return output_tokens def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Tuple = [i for i in token_ids if i >= 0] __lowerCamelCase : str = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[Any]): return token in self.encoder def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str]): return "".join(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.encoder.get(SCREAMING_SNAKE_CASE__ ,self.encoder.get(self.unk_token)) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return self.decoder.get(SCREAMING_SNAKE_CASE__ ,self.unk_token) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if os.path.isdir(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) else: __lowerCamelCase : int = (filename_prefix + '-' if filename_prefix else '') + save_directory __lowerCamelCase : Any = 0 if " " in self.encoder: __lowerCamelCase : Any = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: __lowerCamelCase : str = self.encoder['\n'] del self.encoder["\n"] __lowerCamelCase : str = collections.OrderedDict(sorted(self.encoder.items() ,key=lambda SCREAMING_SNAKE_CASE__: x[1])) with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!') __lowerCamelCase : Any = token_index writer.write(token + '\n') index += 1 return (vocab_file,) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : List[int] = None): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__))
652
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __lowerCAmelCase : Dict ={ "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : str =[ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[str] =[ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[Any] =[ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys __lowerCAmelCase : Optional[Any] =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
440
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a ={"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
652
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """vocab_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt""" ), """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""", """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli""": ( """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """squeezebert/squeezebert-uncased""": 512, """squeezebert/squeezebert-mnli""": 512, """squeezebert/squeezebert-mnli-headless""": 512, } __UpperCAmelCase = { """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowerCamelCase : List[str] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Optional[Any] =PRETRAINED_INIT_CONFIGURATION lowerCamelCase : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : List[Any] =SqueezeBertTokenizer def __init__( self : List[str] , lowerCAmelCase : Tuple=None , lowerCAmelCase : str=None , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : int="[UNK]" , lowerCAmelCase : Dict="[SEP]" , lowerCAmelCase : Dict="[PAD]" , lowerCAmelCase : Optional[int]="[CLS]" , lowerCAmelCase : Union[str, Any]="[MASK]" , lowerCAmelCase : List[Any]=True , lowerCAmelCase : Tuple=None , **lowerCAmelCase : Optional[int] , ) -> Any: """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): __lowerCAmelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop("""type""" ) ) __lowerCAmelCase : Any = do_lower_case __lowerCAmelCase : Optional[Any] = strip_accents __lowerCAmelCase : List[Any] = tokenize_chinese_chars __lowerCAmelCase : int = normalizer_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase : Optional[int] = do_lower_case def SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase : Any , lowerCAmelCase : int=None ) -> Dict: """simple docstring""" __lowerCAmelCase : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Tuple = [self.sep_token_id] __lowerCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> List[str]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
651
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = (UnCLIPScheduler,) def lowerCAmelCase ( self : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Any = { 'num_train_timesteps': 1_0_0_0, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**SCREAMING_SNAKE_CASE__) return config def lowerCAmelCase ( self : Optional[Any]): for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any]): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): for clip_sample_range in [1, 5, 1_0, 2_0]: self.check_over_configs(clip_sample_range=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any]): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): for time_step in [0, 5_0_0, 9_9_9]: for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Any = self.get_scheduler_config(variance_type='fixed_small_log') __lowerCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE__) assert torch.sum(torch.abs(scheduler._get_variance(0) - 1.00_00E-10)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7) - 0.0549625)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9) - 0.9994987)) < 1E-5 def lowerCAmelCase ( self : Any): __lowerCamelCase : Dict = self.scheduler_classes[0] __lowerCamelCase : List[str] = self.get_scheduler_config(variance_type='learned_range') __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = 0.5 assert scheduler._get_variance(1 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -10.1712790 < 1E-5 assert scheduler._get_variance(4_8_7 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -5.7998052 < 1E-5 assert scheduler._get_variance(9_9_9 ,predicted_variance=SCREAMING_SNAKE_CASE__) - -0.0010011 < 1E-5 def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : str = self.get_scheduler_config() __lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = scheduler.timesteps __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter __lowerCamelCase : List[str] = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : int = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # 2. predict previous mean of sample x_t-1 __lowerCamelCase : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Optional[Any] = pred_prev_sample __lowerCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 252.2682495) < 1E-2 assert abs(result_mean.item() - 0.3284743) < 1E-3 def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : List[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**SCREAMING_SNAKE_CASE__) scheduler.set_timesteps(2_5) __lowerCamelCase : int = scheduler.timesteps __lowerCamelCase : Tuple = self.dummy_model() __lowerCamelCase : Any = self.dummy_sample_deter __lowerCamelCase : Any = torch.manual_seed(0) for i, t in enumerate(SCREAMING_SNAKE_CASE__): # 1. predict noise residual __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if i + 1 == timesteps.shape[0]: __lowerCamelCase : Optional[Any] = None else: __lowerCamelCase : Union[str, Any] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __lowerCamelCase : int = scheduler.step( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__).prev_sample __lowerCamelCase : Union[str, Any] = pred_prev_sample __lowerCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__)) assert abs(result_sum.item() - 258.2044983) < 1E-2 assert abs(result_mean.item() - 0.3362038) < 1E-3 def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Union[str, Any]): pass
652
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
125
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''swin2sr''' _UpperCAmelCase : Any = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=1 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : Tuple=1_8_0 ,SCREAMING_SNAKE_CASE__ : Any=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : int=[6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=8 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2.0 ,SCREAMING_SNAKE_CASE__ : Optional[int]=True ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : Any=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Any=False ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-5 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Tuple=1.0 ,SCREAMING_SNAKE_CASE__ : int="1conv" ,SCREAMING_SNAKE_CASE__ : Optional[int]="pixelshuffle" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = image_size __lowerCamelCase : str = patch_size __lowerCamelCase : List[Any] = num_channels __lowerCamelCase : Dict = embed_dim __lowerCamelCase : Dict = depths __lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = num_heads __lowerCamelCase : Tuple = window_size __lowerCamelCase : Dict = mlp_ratio __lowerCamelCase : str = qkv_bias __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[Any] = attention_probs_dropout_prob __lowerCamelCase : List[Any] = drop_path_rate __lowerCamelCase : Optional[int] = hidden_act __lowerCamelCase : Dict = use_absolute_embeddings __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : str = initializer_range __lowerCamelCase : List[Any] = upscale __lowerCamelCase : List[Any] = img_range __lowerCamelCase : List[str] = resi_connection __lowerCamelCase : Union[str, Any] = upsampler
652
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } _SCREAMING_SNAKE_CASE = { "distilbert-base-uncased": 5_12, "distilbert-base-uncased-distilled-squad": 5_12, "distilbert-base-cased": 5_12, "distilbert-base-cased-distilled-squad": 5_12, "distilbert-base-german-cased": 5_12, "distilbert-base-multilingual-cased": 5_12, } _SCREAMING_SNAKE_CASE = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class SCREAMING_SNAKE_CASE_ ( _a ): """simple docstring""" __lowerCAmelCase : Optional[int] =VOCAB_FILES_NAMES __lowerCAmelCase : int =PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase : Any =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase : Any =PRETRAINED_INIT_CONFIGURATION __lowerCAmelCase : int =['''input_ids''', '''attention_mask'''] __lowerCAmelCase : int =DistilBertTokenizer def __init__( self :Union[str, Any], snake_case :List[Any]=None, snake_case :List[str]=None, snake_case :str=True, snake_case :Tuple="[UNK]", snake_case :Tuple="[SEP]", snake_case :Optional[int]="[PAD]", snake_case :Union[str, Any]="[CLS]", snake_case :Union[str, Any]="[MASK]", snake_case :str=True, snake_case :Optional[Any]=None, **snake_case :Any, ): """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__, tokenizer_file=SCREAMING_SNAKE_CASE__, do_lower_case=SCREAMING_SNAKE_CASE__, unk_token=SCREAMING_SNAKE_CASE__, sep_token=SCREAMING_SNAKE_CASE__, pad_token=SCREAMING_SNAKE_CASE__, cls_token=SCREAMING_SNAKE_CASE__, mask_token=SCREAMING_SNAKE_CASE__, tokenize_chinese_chars=SCREAMING_SNAKE_CASE__, strip_accents=SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__, ) _lowercase =json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase', SCREAMING_SNAKE_CASE__) != do_lower_case or normalizer_state.get('strip_accents', SCREAMING_SNAKE_CASE__) != strip_accents or normalizer_state.get('handle_chinese_chars', SCREAMING_SNAKE_CASE__) != tokenize_chinese_chars ): _lowercase =getattr(SCREAMING_SNAKE_CASE__, normalizer_state.pop('type')) _lowercase =do_lower_case _lowercase =strip_accents _lowercase =tokenize_chinese_chars _lowercase =normalizer_class(**SCREAMING_SNAKE_CASE__) _lowercase =do_lower_case def UpperCamelCase__ ( self :Dict, snake_case :Dict, snake_case :Tuple=None): """simple docstring""" _lowercase =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase__ ( self :Dict, snake_case :List[int], snake_case :Optional[List[int]] = None): """simple docstring""" _lowercase =[self.sep_token_id] _lowercase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def UpperCamelCase__ ( self :Optional[int], snake_case :str, snake_case :Optional[str] = None): """simple docstring""" _lowercase =self._tokenizer.model.save(SCREAMING_SNAKE_CASE__, name=SCREAMING_SNAKE_CASE__) return tuple(SCREAMING_SNAKE_CASE__)
181
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__="pt" ) -> Dict: __lowerCamelCase : Any = {'add_prefix_space': True} if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not line.startswith(' ' ) else {} __lowerCamelCase : int = padding_side return tokenizer( [line] , max_length=lowerCamelCase__ , padding='max_length' if pad_to_max_length else None , truncation=lowerCamelCase__ , return_tensors=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , ) -> List[str]: __lowerCamelCase : List[str] = input_ids.ne(lowerCamelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]="train" ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[Any]="" ,): super().__init__() __lowerCamelCase : Optional[Any] = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.source') __lowerCamelCase : Any = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.target') __lowerCamelCase : List[Any] = self.get_char_lens(self.src_file) __lowerCamelCase : List[Any] = max_source_length __lowerCamelCase : List[str] = max_target_length assert min(self.src_lens) > 0, F"found empty line in {self.src_file}" __lowerCamelCase : Any = tokenizer __lowerCamelCase : Optional[int] = prefix if n_obs is not None: __lowerCamelCase : Dict = self.src_lens[:n_obs] __lowerCamelCase : str = src_lang __lowerCamelCase : Any = tgt_lang def __len__( self : Tuple): return len(self.src_lens) def __getitem__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Dict = index + 1 # linecache starts at 1 __lowerCamelCase : Any = self.prefix + linecache.getline(str(self.src_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') __lowerCamelCase : int = linecache.getline(str(self.tgt_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n') assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __lowerCamelCase : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer ) __lowerCamelCase : Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer __lowerCamelCase : List[str] = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_source_length ,'right') __lowerCamelCase : Any = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_target_length ,'right') __lowerCamelCase : List[Any] = source_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = target_inputs['input_ids'].squeeze() __lowerCamelCase : Tuple = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : int): return [len(SCREAMING_SNAKE_CASE__) for x in Path(SCREAMING_SNAKE_CASE__).open().readlines()] def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[Any] = torch.stack([x['input_ids'] for x in batch]) __lowerCamelCase : Any = torch.stack([x['attention_mask'] for x in batch]) __lowerCamelCase : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch]) __lowerCamelCase : Optional[int] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer.pad_token_id ) __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch a =getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return list(itertools.chain.from_iterable(lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: __lowerCamelCase : str = get_git_info() save_json(lowerCamelCase__ , os.path.join(lowerCamelCase__ , 'git_log.json' ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=4 , **lowerCamelCase__ ) -> List[str]: with open(lowerCamelCase__ , 'w' ) as f: json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=lowerCamelCase__ , **lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: with open(lowerCamelCase__ ) as f: return json.load(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: __lowerCamelCase : str = git.Repo(search_parent_directories=lowerCamelCase__ ) __lowerCamelCase : Any = { 'repo_id': str(lowerCamelCase__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List: return list(map(lowerCamelCase__ , lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: with open(lowerCamelCase__ , 'wb' ) as f: return pickle.dump(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: def remove_articles(lowerCamelCase__ ): return re.sub(R'\b(a|an|the)\b' , ' ' , lowerCamelCase__ ) def white_space_fix(lowerCamelCase__ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase__ ): __lowerCamelCase : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : str = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Optional[int] = normalize_answer(lowerCamelCase__ ).split() __lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) & Counter(lowerCamelCase__ ) __lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 __lowerCamelCase : List[Any] = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : int = 1.0 * num_same / len(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: return normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ) __lowerCamelCase : Dict = 0 for hypo, pred in zip(lowerCamelCase__ , lowerCamelCase__ ): em += exact_match_score(lowerCamelCase__ , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: em /= len(lowerCamelCase__ ) return {"em": em} def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return model_prefix.startswith('rag' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __lowerCamelCase : List[str] = 'dropout_rate' for p in extra_params: if getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if not hasattr(lowerCamelCase__ , lowerCamelCase__ ) and not hasattr(lowerCamelCase__ , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) continue __lowerCamelCase : List[Any] = p if hasattr(lowerCamelCase__ , lowerCamelCase__ ) else equivalent_param[p] setattr(lowerCamelCase__ , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) delattr(lowerCamelCase__ , lowerCamelCase__ ) return hparams, config
652
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
341
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a =logging.get_logger(__name__) # General docstring a ="""MobileNetV1Config""" # Base docstring a ="""google/mobilenet_v1_1.0_224""" a =[1, 1024, 7, 7] # Image classification docstring a ="""google/mobilenet_v1_1.0_224""" a ="""tabby, tabby cat""" a =[ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> str: __lowerCamelCase : str = {} if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = model.mobilenet_va else: __lowerCamelCase : List[str] = model __lowerCamelCase : List[Any] = 'MobilenetV1/Conv2d_0/' __lowerCamelCase : List[Any] = backbone.conv_stem.convolution.weight __lowerCamelCase : List[str] = backbone.conv_stem.normalization.bias __lowerCamelCase : Tuple = backbone.conv_stem.normalization.weight __lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean __lowerCamelCase : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(1_3 ): __lowerCamelCase : Any = i + 1 __lowerCamelCase : Union[str, Any] = i * 2 __lowerCamelCase : Optional[Any] = backbone.layer[pt_index] __lowerCamelCase : Optional[int] = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" __lowerCamelCase : Tuple = pointer.convolution.weight __lowerCamelCase : Optional[Any] = pointer.normalization.bias __lowerCamelCase : Union[str, Any] = pointer.normalization.weight __lowerCamelCase : List[str] = pointer.normalization.running_mean __lowerCamelCase : Union[str, Any] = pointer.normalization.running_var __lowerCamelCase : int = backbone.layer[pt_index + 1] __lowerCamelCase : Union[str, Any] = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" __lowerCamelCase : Optional[Any] = pointer.convolution.weight __lowerCamelCase : Any = pointer.normalization.bias __lowerCamelCase : str = pointer.normalization.weight __lowerCamelCase : Dict = pointer.normalization.running_mean __lowerCamelCase : List[str] = pointer.normalization.running_var if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __lowerCamelCase : Any = model.classifier.weight __lowerCamelCase : int = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __lowerCamelCase : List[str] = tf.train.list_variables(lowerCamelCase__ ) __lowerCamelCase : List[str] = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) __lowerCamelCase : Any = tf.train.load_variable(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[Any] = array # Build TF to PyTorch weights loading map __lowerCamelCase : Tuple = _build_tf_to_pytorch_map(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue __lowerCamelCase : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __lowerCamelCase : List[str] = np.transpose(lowerCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __lowerCamelCase : Any = array.squeeze().transpose() else: __lowerCamelCase : Tuple = np.transpose(lowerCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) __lowerCamelCase : Optional[Any] = torch.from_numpy(lowerCamelCase__ ) tf_weights.pop(lowerCamelCase__ , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp' , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp_1' , lowerCamelCase__ ) tf_weights.pop(name + '/ExponentialMovingAverage' , lowerCamelCase__ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: __lowerCamelCase , __lowerCamelCase : int = features.shape[-2:] __lowerCamelCase , __lowerCamelCase : List[str] = conv_layer.stride __lowerCamelCase , __lowerCamelCase : str = conv_layer.kernel_size if in_height % stride_height == 0: __lowerCamelCase : Optional[int] = max(kernel_height - stride_height , 0 ) else: __lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __lowerCamelCase : List[str] = max(kernel_width - stride_width , 0 ) else: __lowerCamelCase : List[str] = max(kernel_width - (in_width % stride_width) , 0 ) __lowerCamelCase : List[str] = pad_along_width // 2 __lowerCamelCase : Optional[int] = pad_along_width - pad_left __lowerCamelCase : Any = pad_along_height // 2 __lowerCamelCase : List[Any] = pad_along_height - pad_top __lowerCamelCase : Union[str, Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(lowerCamelCase__ , lowerCamelCase__ , 'constant' , 0.0 ) class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[bool or str] = True ,): super().__init__() __lowerCamelCase : Dict = config if in_channels % groups != 0: raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups.") if out_channels % groups != 0: raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups.") __lowerCamelCase : Optional[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2) __lowerCamelCase : Optional[int] = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__ ,padding_mode='zeros' ,) if use_normalization: __lowerCamelCase : Optional[int] = nn.BatchNormad( num_features=SCREAMING_SNAKE_CASE__ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=SCREAMING_SNAKE_CASE__ ,track_running_stats=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Dict = None if use_activation: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = ACTaFN[use_activation] elif isinstance(config.hidden_act ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = ACTaFN[config.hidden_act] else: __lowerCamelCase : List[str] = config.hidden_act else: __lowerCamelCase : List[str] = None def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): if self.config.tf_padding: __lowerCamelCase : Any = apply_tf_padding(SCREAMING_SNAKE_CASE__ ,self.convolution) __lowerCamelCase : Optional[int] = self.convolution(SCREAMING_SNAKE_CASE__) if self.normalization is not None: __lowerCamelCase : Dict = self.normalization(SCREAMING_SNAKE_CASE__) if self.activation is not None: __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return features class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = MobileNetVaConfig _UpperCAmelCase : List[str] = load_tf_weights_in_mobilenet_va _UpperCAmelCase : List[str] = '''mobilenet_v1''' _UpperCAmelCase : Any = '''pixel_values''' _UpperCAmelCase : int = False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[nn.Linear, nn.Convad]): if isinstance(SCREAMING_SNAKE_CASE__ ,(nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ ,nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : bool = True): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = config __lowerCamelCase : Optional[int] = 3_2 __lowerCamelCase : List[str] = max(int(depth * config.depth_multiplier) ,config.min_depth) __lowerCamelCase : Optional[Any] = MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=config.num_channels ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=2 ,) __lowerCamelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __lowerCamelCase : str = nn.ModuleList() for i in range(1_3): __lowerCamelCase : str = out_channels if strides[i] == 2 or i == 0: depth *= 2 __lowerCamelCase : str = max(int(depth * config.depth_multiplier) ,config.min_depth) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=strides[i] ,groups=SCREAMING_SNAKE_CASE__ ,)) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,)) __lowerCamelCase : Optional[int] = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') __lowerCamelCase : Optional[Any] = self.conv_stem(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Any = all_hidden_states + (hidden_states,) __lowerCamelCase : Optional[Any] = hidden_states if self.pooler is not None: __lowerCamelCase : Tuple = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__) ,start_dim=1) else: __lowerCamelCase : List[str] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = config.num_labels __lowerCamelCase : Optional[Any] = MobileNetVaModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __lowerCamelCase : Any = nn.Dropout(config.classifier_dropout_prob ,inplace=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Optional[int] = self.mobilenet_va(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] = self.classifier(self.dropout(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : int = 'single_label_classification' else: __lowerCamelCase : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : Tuple = MSELoss() if self.num_labels == 1: __lowerCamelCase : int = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : Union[str, Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : List[str] = CrossEntropyLoss() __lowerCamelCase : List[str] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : int = BCEWithLogitsLoss() __lowerCamelCase : int = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states ,)
652
0
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig lowercase__ = logging.get_logger(__name__) # General docstring lowercase__ = "RegNetConfig" # Base docstring lowercase__ = "facebook/regnet-y-040" lowercase__ = [1, 1_0_8_8, 7, 7] # Image classification docstring lowercase__ = "facebook/regnet-y-040" lowercase__ = "tabby, tabby cat" lowercase__ = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : int = 3 , UpperCamelCase__ : int = 1 , UpperCamelCase__ : int = 1 , UpperCamelCase__ : Optional[str] = "relu" , **UpperCamelCase__ : Optional[int] , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb snake_case : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) snake_case : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , strides=SCREAMING_SNAKE_CASE__ , padding='''VALID''' , groups=SCREAMING_SNAKE_CASE__ , use_bias=SCREAMING_SNAKE_CASE__ , name='''convolution''' , ) snake_case : int = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) snake_case : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any , UpperCamelCase__ : List[str] ) -> Any: """simple docstring""" snake_case : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__ ) ) snake_case : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = self.activation(SCREAMING_SNAKE_CASE__ ) return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : str , UpperCamelCase__ : RegNetConfig , **UpperCamelCase__ : Dict ) -> Optional[int]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Optional[int] = config.num_channels snake_case : Dict = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def lowerCAmelCase ( self : Tuple , UpperCamelCase__ : List[Any] ) -> Union[str, Any]: """simple docstring""" snake_case : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) snake_case : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ , perm=(0, 2, 3, 1) ) snake_case : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__ ) return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : int = 2 , **UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ , kernel_size=1 , strides=SCREAMING_SNAKE_CASE__ , use_bias=SCREAMING_SNAKE_CASE__ , name='''convolution''' ) snake_case : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def lowerCAmelCase ( self : Dict , UpperCamelCase__ : tf.Tensor , UpperCamelCase__ : bool = False ) -> Any: """simple docstring""" return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__ ) , training=SCREAMING_SNAKE_CASE__ ) class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : int , UpperCamelCase__ : int , UpperCamelCase__ : int , **UpperCamelCase__ : Any ) -> List[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ , name='''pooler''' ) snake_case : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : int ) -> List[str]: """simple docstring""" snake_case : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__ ) for layer_module in self.attention: snake_case : Any = layer_module(SCREAMING_SNAKE_CASE__ ) snake_case : Optional[int] = hidden_state * pooled return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Union[str, Any] , UpperCamelCase__ : RegNetConfig , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int = 1 , **UpperCamelCase__ : List[Any] ) -> List[str]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Tuple = in_channels != out_channels or stride != 1 snake_case : Union[str, Any] = max(1 , out_channels // config.groups_width ) snake_case : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. snake_case : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , groups=SCREAMING_SNAKE_CASE__ , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation=SCREAMING_SNAKE_CASE__ , name='''layer.2''' ), ] snake_case : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] , UpperCamelCase__ : Optional[int] ) -> str: """simple docstring""" snake_case : int = hidden_state for layer_module in self.layers: snake_case : List[str] = layer_module(SCREAMING_SNAKE_CASE__ ) snake_case : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__ ) hidden_state += residual snake_case : int = self.activation(SCREAMING_SNAKE_CASE__ ) return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Optional[Any] , UpperCamelCase__ : RegNetConfig , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int = 1 , **UpperCamelCase__ : List[str] ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Optional[Any] = in_channels != out_channels or stride != 1 snake_case : Tuple = max(1 , out_channels // config.groups_width ) snake_case : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) snake_case : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , groups=SCREAMING_SNAKE_CASE__ , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ , kernel_size=1 , activation=SCREAMING_SNAKE_CASE__ , name='''layer.3''' ), ] snake_case : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any , UpperCamelCase__ : str ) -> int: """simple docstring""" snake_case : Optional[int] = hidden_state for layer_module in self.layers: snake_case : Dict = layer_module(SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__ ) hidden_state += residual snake_case : Any = self.activation(SCREAMING_SNAKE_CASE__ ) return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : int , UpperCamelCase__ : RegNetConfig , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : int = 2 , UpperCamelCase__ : int = 2 , **UpperCamelCase__ : Tuple ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer snake_case : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , name='''layers.0''' ), *[layer(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , name=f'layers.{i+1}' ) for i in range(depth - 1 )], ] def lowerCAmelCase ( self : Any , UpperCamelCase__ : List[Any] ) -> List[str]: """simple docstring""" for layer_module in self.layers: snake_case : Any = layer_module(SCREAMING_SNAKE_CASE__ ) return hidden_state class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Optional[int] , UpperCamelCase__ : RegNetConfig , **UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) snake_case : Optional[int] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , depth=SCREAMING_SNAKE_CASE__ , name=f'stages.{i+1}' ) ) def lowerCAmelCase ( self : Dict , UpperCamelCase__ : tf.Tensor , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = True ) -> Dict: """simple docstring""" snake_case : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: snake_case : Optional[Any] = hidden_states + (hidden_state,) snake_case : str = stage_module(SCREAMING_SNAKE_CASE__ ) if output_hidden_states: snake_case : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) @keras_serializable class snake_case__ ( tf.keras.layers.Layer ): """simple docstring""" lowerCamelCase = RegNetConfig def __init__( self : List[Any] , UpperCamelCase__ : int , **UpperCamelCase__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = config snake_case : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ , name='''embedder''' ) snake_case : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ , name='''encoder''' ) snake_case : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ , name='''pooler''' ) @unpack_inputs def lowerCAmelCase ( self : Optional[Any] , UpperCamelCase__ : tf.Tensor , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : bool = False , ) -> Union[str, Any]: """simple docstring""" snake_case : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) snake_case : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) snake_case : Optional[int] = encoder_outputs[0] snake_case : int = self.pooler(SCREAMING_SNAKE_CASE__ ) # Change to NCHW output format have uniformity in the modules snake_case : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ , perm=(0, 3, 1, 2) ) snake_case : str = tf.transpose(SCREAMING_SNAKE_CASE__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: snake_case : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , pooler_output=SCREAMING_SNAKE_CASE__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase = RegNetConfig lowerCamelCase = '''regnet''' lowerCamelCase = '''pixel_values''' @property def lowerCAmelCase ( self : int ) -> Optional[int]: """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} lowercase__ = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" lowercase__ = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""" , __SCREAMING_SNAKE_CASE , ) class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : List[Any] , UpperCamelCase__ : RegNetConfig , *UpperCamelCase__ : Tuple , **UpperCamelCase__ : Tuple ) -> Optional[Any]: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCAmelCase ( self : List[str] , UpperCamelCase__ : tf.Tensor , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : int=False , ) -> Optional[int]: """simple docstring""" snake_case : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict snake_case : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , __SCREAMING_SNAKE_CASE , ) class snake_case__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : Any , UpperCamelCase__ : RegNetConfig , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : str ) -> List[str]: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case : Union[str, Any] = config.num_labels snake_case : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ , name='''regnet''' ) # classification head snake_case : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : tf.Tensor = None , UpperCamelCase__ : tf.Tensor = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Any=False , ) -> Union[str, Any]: """simple docstring""" snake_case : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case : Tuple = return_dict if return_dict is not None else self.config.use_return_dict snake_case : str = self.regnet( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = outputs.pooler_output if return_dict else outputs[1] snake_case : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__ ) snake_case : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__ ) snake_case : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
638
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = cva.getAffineTransform(lowerCamelCase__ , lowerCamelCase__ ) return cva.warpAffine(lowerCamelCase__ , lowerCamelCase__ , (rows, cols) ) if __name__ == "__main__": # read original image a =cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value a =cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a , a =gray_img.shape # set different points to rotate image a =np.array([[50, 50], [200, 50], [50, 200]], np.floataa) a =np.array([[10, 100], [200, 50], [100, 250]], np.floataa) a =np.array([[50, 50], [150, 50], [120, 200]], np.floataa) a =np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list a =[ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a =plt.figure(1) a =["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
652
0
from __future__ import annotations from math import pow, sqrt def __lowerCamelCase ( lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[str] ): '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance == 0: return {"resistance": sqrt(pow(lowerCamelCase__ , 2 ) - pow(lowerCamelCase__ , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(lowerCamelCase__ , 2 ) - pow(lowerCamelCase__ , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(lowerCamelCase__ , 2 ) + pow(lowerCamelCase__ , 2 ) )} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
457
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : List[str] = F"Input value of [number={number}] must be an integer" raise TypeError(lowerCamelCase__ ) if number < 1: __lowerCamelCase : int = F"Input value of [number={number}] must be > 0" raise ValueError(lowerCamelCase__ ) elif number == 1: return 3 elif number == 2: return 5 else: __lowerCamelCase : Any = int(math.log(number // 3 , 2 ) ) + 2 __lowerCamelCase : List[Any] = [3, 5] __lowerCamelCase : Union[str, Any] = 2 __lowerCamelCase : List[str] = 3 for block in range(1 , lowerCamelCase__ ): for _ in range(lowerCamelCase__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): a =0 try: a =proth(number) except ValueError: print(F"""ValueError: there is no {number}th Proth number""") continue print(F"""The {number}th Proth number: {value}""")
652
0
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _UpperCAmelCase ( lowerCAmelCase_ ): a : List[str] =(UniPCMultistepScheduler,) a : int =(('''num_inference_steps''', 25),) def lowerCamelCase__ ( self,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = { 'num_train_timesteps': 10_00, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'solver_type': 'bh2', } config.update(**SCREAMING_SNAKE_CASE__ ) return config def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE=0,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = dict(self.forward_default_kwargs ) __lowerCAmelCase = kwargs.pop("""num_inference_steps""",SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.dummy_sample __lowerCAmelCase = 0.1 * sample __lowerCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __lowerCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals __lowerCAmelCase = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals __lowerCAmelCase = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCAmelCase = sample, sample for t in range(SCREAMING_SNAKE_CASE__,time_step + scheduler.config.solver_order + 1 ): __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample __lowerCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE=0,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = dict(self.forward_default_kwargs ) __lowerCAmelCase = kwargs.pop("""num_inference_steps""",SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.dummy_sample __lowerCAmelCase = 0.1 * sample __lowerCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals (must be after setting timesteps) __lowerCAmelCase = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # copy over dummy past residual (must be after setting timesteps) __lowerCAmelCase = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample __lowerCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE=None,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' if scheduler is None: __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = 10 __lowerCAmelCase = self.dummy_model() __lowerCAmelCase = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ).prev_sample return sample def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = dict(self.forward_default_kwargs ) __lowerCAmelCase = kwargs.pop("""num_inference_steps""",SCREAMING_SNAKE_CASE__ ) for scheduler_class in self.scheduler_classes: __lowerCAmelCase = self.get_scheduler_config() __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.dummy_sample __lowerCAmelCase = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE__,"""set_timesteps""" ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE__,"""set_timesteps""" ): __lowerCAmelCase = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __lowerCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.10] __lowerCAmelCase = dummy_past_residuals[: scheduler.config.solver_order] __lowerCAmelCase = scheduler.timesteps[5] __lowerCAmelCase = scheduler.timesteps[6] __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ).prev_sample self.assertEqual(output_a.shape,sample.shape ) self.assertEqual(output_a.shape,output_a.shape ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = UniPCMultistepScheduler(**self.get_scheduler_config() ) __lowerCAmelCase = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 __lowerCAmelCase = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __lowerCAmelCase = DEISMultistepScheduler.from_config(scheduler.config ) __lowerCAmelCase = DPMSolverMultistepScheduler.from_config(scheduler.config ) __lowerCAmelCase = UniPCMultistepScheduler.from_config(scheduler.config ) __lowerCAmelCase = self.full_loop(scheduler=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 def lowerCamelCase__ ( self ): '''simple docstring''' for timesteps in [25, 50, 1_00, 9_99, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__,prediction_type=SCREAMING_SNAKE_CASE__,sample_max_value=SCREAMING_SNAKE_CASE__,solver_order=SCREAMING_SNAKE_CASE__,solver_type=SCREAMING_SNAKE_CASE__,) def lowerCamelCase__ ( self ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self ): '''simple docstring''' for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE__,solver_type=SCREAMING_SNAKE_CASE__,prediction_type=SCREAMING_SNAKE_CASE__,) __lowerCAmelCase = self.full_loop( solver_order=SCREAMING_SNAKE_CASE__,solver_type=SCREAMING_SNAKE_CASE__,prediction_type=SCREAMING_SNAKE_CASE__,) assert not torch.isnan(SCREAMING_SNAKE_CASE__ ).any(), "Samples have nan numbers" def lowerCamelCase__ ( self ): '''simple docstring''' self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__ ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self ): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE__,time_step=0 ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.full_loop() __lowerCAmelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.2464 ) < 1e-3 def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.full_loop(prediction_type="""v_prediction""" ) __lowerCAmelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_mean.item() - 0.1014 ) < 1e-3 def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.scheduler_classes[0] __lowerCAmelCase = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE__,dynamic_thresholding_ratio=0 ) __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = 10 __lowerCAmelCase = self.dummy_model() __lowerCAmelCase = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ).prev_sample assert sample.dtype == torch.floataa def lowerCamelCase__ ( self,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' for scheduler_class in self.scheduler_classes: __lowerCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
689
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class A_ ( unittest.TestCase ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=7 ,SCREAMING_SNAKE_CASE__ : Any=3 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0 ,SCREAMING_SNAKE_CASE__ : int=4_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[str]=1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : Tuple=True ,): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __lowerCamelCase : List[Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} __lowerCamelCase : str = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : int = num_channels __lowerCamelCase : Dict = min_resolution __lowerCamelCase : Tuple = max_resolution __lowerCamelCase : Dict = do_resize __lowerCamelCase : List[Any] = size __lowerCamelCase : Tuple = do_normalize __lowerCamelCase : Any = image_mean __lowerCamelCase : List[str] = image_std __lowerCamelCase : List[Any] = do_rescale __lowerCamelCase : str = rescale_factor __lowerCamelCase : Tuple = do_pad def lowerCAmelCase ( self : Dict): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=False): if not batched: __lowerCamelCase : Optional[Any] = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ ,Image.Image): __lowerCamelCase , __lowerCamelCase : Any = image.size else: __lowerCamelCase , __lowerCamelCase : Any = image.shape[1], image.shape[2] if w < h: __lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w) __lowerCamelCase : Tuple = self.size['shortest_edge'] elif w > h: __lowerCamelCase : Union[str, Any] = self.size['shortest_edge'] __lowerCamelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h) else: __lowerCamelCase : List[Any] = self.size['shortest_edge'] __lowerCamelCase : Optional[int] = self.size['shortest_edge'] else: __lowerCamelCase : List[str] = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase : List[Any] = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) __lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[0])[0] __lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[1])[1] return expected_height, expected_width @require_torch @require_vision class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[int] = DetaImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = DetaImageProcessingTester(self) @property def lowerCAmelCase ( self : Any): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_mean')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_std')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_normalize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_resize')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_rescale')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_pad')) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'size')) def lowerCAmelCase ( self : str): __lowerCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size ,{'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}) self.assertEqual(image_processor.do_pad ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): pass def lowerCAmelCase ( self : List[str]): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random PIL images __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,Image.Image) # Test not batched input __lowerCamelCase : List[Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : str): # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,numpify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,np.ndarray) # Test not batched input __lowerCamelCase : Tuple = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def lowerCAmelCase ( self : int): # Initialize image_processing __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,torchify=SCREAMING_SNAKE_CASE__) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,torch.Tensor) # Test not batched input __lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched __lowerCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) @slow def lowerCAmelCase ( self : Optional[Any]): # prepare image and target __lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r') as f: __lowerCamelCase : List[str] = json.loads(f.read()) __lowerCamelCase : Union[str, Any] = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them __lowerCamelCase : Optional[int] = DetaImageProcessor() __lowerCamelCase : int = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Dict = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : int = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : Tuple = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : List[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify orig_size __lowerCamelCase : str = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : int = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__)) @slow def lowerCAmelCase ( self : str): # prepare image, target and masks_path __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r') as f: __lowerCamelCase : Tuple = json.loads(f.read()) __lowerCamelCase : List[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} __lowerCamelCase : Optional[int] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them __lowerCamelCase : List[str] = DetaImageProcessor(format='coco_panoptic') __lowerCamelCase : Optional[Any] = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,masks_path=SCREAMING_SNAKE_CASE__ ,return_tensors='pt') # verify pixel values __lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6]) self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify area __lowerCamelCase : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__)) # verify boxes __lowerCamelCase : Tuple = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3)) # verify image_id __lowerCamelCase : int = torch.tensor([3_9_7_6_9]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__)) # verify is_crowd __lowerCamelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__)) # verify class_labels __lowerCamelCase : int = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__)) # verify masks __lowerCamelCase : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,SCREAMING_SNAKE_CASE__) # verify orig_size __lowerCamelCase : Any = torch.tensor([4_8_0, 6_4_0]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__)) # verify size __lowerCamelCase : Any = torch.tensor([8_0_0, 1_0_6_6]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
652
0
import doctest from collections import deque import numpy as np class UpperCamelCase_ : '''simple docstring''' def __init__( self) -> Dict: UpperCamelCase__ : Dict = [2, 1, 2, -1] UpperCamelCase__ : List[Any] = [1, 2, 3, 4] def lowerCAmelCase__ ( self) -> Optional[int]: UpperCamelCase__ : Dict = len(self.first_signal) UpperCamelCase__ : str = len(self.second_signal) UpperCamelCase__ : Dict = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # create a zero matrix of max_length x max_length UpperCamelCase__ : Optional[Any] = [[0] * max_length for i in range(SCREAMING_SNAKE_CASE__)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(SCREAMING_SNAKE_CASE__): UpperCamelCase__ : Dict = deque(self.second_signal) rotated_signal.rotate(SCREAMING_SNAKE_CASE__) for j, item in enumerate(SCREAMING_SNAKE_CASE__): matrix[i][j] += item # multiply the matrix with the first signal UpperCamelCase__ : Union[str, Any] = np.matmul(np.transpose(SCREAMING_SNAKE_CASE__) , np.transpose(self.first_signal)) # rounding-off to two decimal places return [round(SCREAMING_SNAKE_CASE__ , 2) for i in final_signal] if __name__ == "__main__": doctest.testmod()
410
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_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Optional[Any] = KandinskyVaaControlnetPipeline _UpperCAmelCase : Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : int = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] _UpperCAmelCase : List[Any] = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _UpperCAmelCase : Tuple = False @property def lowerCAmelCase ( self : Tuple): return 3_2 @property def lowerCAmelCase ( self : List[Any]): return 3_2 @property def lowerCAmelCase ( self : str): return self.time_input_dim @property def lowerCAmelCase ( self : List[str]): return self.time_input_dim * 4 @property def lowerCAmelCase ( self : List[str]): return 1_0_0 @property def lowerCAmelCase ( self : Dict): torch.manual_seed(0) __lowerCamelCase : 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, } __lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__) return model @property def lowerCAmelCase ( self : Union[str, Any]): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Optional[Any]): torch.manual_seed(0) __lowerCamelCase : int = VQModel(**self.dummy_movq_kwargs) return model def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = self.dummy_unet __lowerCamelCase : List[Any] = self.dummy_movq __lowerCamelCase : str = DDIMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='linear' ,beta_start=0.00085 ,beta_end=0.012 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Dict = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=0): __lowerCamelCase : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1)).to( SCREAMING_SNAKE_CASE__) # create hint __lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) if str(SCREAMING_SNAKE_CASE__).startswith('mps'): __lowerCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 6_4, 'width': 6_4, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = 'cpu' __lowerCamelCase : Tuple = self.get_dummy_components() __lowerCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : int = output.images __lowerCamelCase : Tuple = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) ,return_dict=SCREAMING_SNAKE_CASE__ ,)[0] __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : List[str] = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]) assert ( np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : int): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy') __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png') __lowerCamelCase : Tuple = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 255.0 __lowerCamelCase : str = hint.permute(2 ,0 ,1).unsqueeze(0) __lowerCamelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa) pipe_prior.to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' ,torch_dtype=torch.floataa) __lowerCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE__) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 'A robot, 4k photo' __lowerCamelCase : List[str] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe_prior( SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple() __lowerCamelCase : Optional[Any] = torch.Generator(device='cuda').manual_seed(0) __lowerCamelCase : Any = pipeline( image_embeds=SCREAMING_SNAKE_CASE__ ,negative_image_embeds=SCREAMING_SNAKE_CASE__ ,hint=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
652
0
'''simple docstring''' from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : Dict = logging.get_logger(__name__) A : Optional[Any] = { '''nielsr/canine-s''': 2048, } # Unicode defines 1,114,112 total “codepoints” A : Optional[Any] = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py A : Dict = 0 A : List[Any] = 0XE000 A : List[Any] = 0XE001 A : Tuple = 0XE002 A : Optional[Any] = 0XE003 A : Any = 0XE004 # Maps special codepoints to human-readable names. A : str = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: '''[CLS]''', SEP: '''[SEP]''', BOS: '''[BOS]''', MASK: '''[MASK]''', PAD: '''[PAD]''', RESERVED: '''[RESERVED]''', } # Maps special codepoint human-readable names to their codepoint values. A : Tuple = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class __lowerCamelCase ( a_ ): """simple docstring""" a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[int]=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : Optional[Any]=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : List[Any]=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : int=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : Any=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : Optional[Any]=chr(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE : Any=False , SCREAMING_SNAKE_CASE : int=2048 , **SCREAMING_SNAKE_CASE : int , ): _A : List[str] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else bos_token _A : Tuple = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else eos_token _A : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else sep_token _A : List[str] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else cls_token _A : Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else pad_token # Mask token behave like a normal word, i.e. include the space before it _A : Any = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) else mask_token super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , model_max_length=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # Creates a mapping for looking up the IDs of special symbols. _A : Dict[str, int] = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): _A : int = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. _A : Dict[int, str] = { codepoint: name for name, codepoint in self._special_codepoints.items() } _A : str = UNICODE_VOCAB_SIZE _A : Dict = len(self._special_codepoints) @property def A ( self : int): return self._unicode_vocab_size def A ( self : Dict , SCREAMING_SNAKE_CASE : str): return list(SCREAMING_SNAKE_CASE__) def A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : str): try: return ord(SCREAMING_SNAKE_CASE__) except TypeError: raise ValueError(F'invalid token: \'{token}\'') def A ( self : Optional[Any] , SCREAMING_SNAKE_CASE : int): try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(SCREAMING_SNAKE_CASE__) except TypeError: raise ValueError(F'invalid id: {index}') def A ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Dict): return "".join(SCREAMING_SNAKE_CASE__) def A ( self : Tuple , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None): _A : Union[str, Any] = [self.sep_token_id] _A : Dict = [self.cls_token_id] _A : int = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def A ( self : List[Any] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None , SCREAMING_SNAKE_CASE : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__) _A : Tuple = [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] if token_ids_a is not None: result += ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return result def A ( self : List[Any] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None): _A : List[str] = [self.sep_token_id] _A : Union[str, Any] = [self.cls_token_id] _A : str = len(cls + token_ids_a + sep) * [0] if token_ids_a is not None: result += len(token_ids_a + sep) * [1] return result def A ( self : Optional[int] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[str] = None): return ()
128
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : _UpperCAmelCase : int = XGLMConfig _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Tuple = '''gelu''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 ,SCREAMING_SNAKE_CASE__ : Tuple=7 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=9_9 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : Tuple=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,): __lowerCamelCase : List[str] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_input_mask __lowerCamelCase : str = use_labels __lowerCamelCase : Any = vocab_size __lowerCamelCase : Dict = d_model __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : List[str] = ffn_dim __lowerCamelCase : Optional[Any] = activation_function __lowerCamelCase : Tuple = activation_dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Any = None __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 2 __lowerCamelCase : Dict = 1 def lowerCAmelCase ( self : Any): return XGLMConfig.from_pretrained('facebook/xglm-564M') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) ,clip_value_min=0 ,clip_value_max=3) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : int = self.get_config() __lowerCamelCase : Union[str, Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2) return ( config, input_ids, input_mask, head_mask, ) def lowerCAmelCase ( self : List[Any]): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=SCREAMING_SNAKE_CASE__ ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : int): __lowerCamelCase : int = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : str = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : str = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _UpperCAmelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else () _UpperCAmelCase : str = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) _UpperCAmelCase : Tuple = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Tuple = TFXGLMModelTester(self) __lowerCamelCase : int = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,n_embd=3_7) def lowerCAmelCase ( self : List[Any]): self.config_tester.run_common_tests() @slow def lowerCAmelCase ( self : str): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.') def lowerCAmelCase ( self : Union[str, Any]): super().test_resize_token_embeddings() @require_tf class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True): __lowerCamelCase : Any = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]] ,dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __lowerCamelCase : Optional[Any] = [2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1] # fmt: on __lowerCamelCase : int = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Tuple = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') tf.random.set_seed(0) __lowerCamelCase : Optional[Any] = tokenizer('Today is a nice day and' ,return_tensors='tf') __lowerCamelCase : List[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0'): __lowerCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE__ ,do_sample=SCREAMING_SNAKE_CASE__ ,seed=[7, 0]) __lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M') __lowerCamelCase : Union[str, Any] = 'left' # use different length sentences to test batching __lowerCamelCase : List[str] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __lowerCamelCase : List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='tf' ,padding=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = inputs['input_ids'] __lowerCamelCase : Dict = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,attention_mask=inputs['attention_mask'] ,max_new_tokens=1_2) __lowerCamelCase : Tuple = tokenizer(sentences[0] ,return_tensors='tf').input_ids __lowerCamelCase : List[str] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : Any = tokenizer(sentences[1] ,return_tensors='tf').input_ids __lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ,max_new_tokens=1_2) __lowerCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tokenizer.decode(output_padded[0] ,skip_special_tokens=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[non_padded_sentence, padded_sentence])
652
0
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __snake_case : Optional[Any] = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class UpperCamelCase ( unittest.TestCase ): """simple docstring""" def A__ ( self : List[str] , _lowerCamelCase : Path , _lowerCamelCase : Union[str, None] = None , _lowerCamelCase : Union[List[str], None] = None , _lowerCamelCase : Union[str, List[str], None] = None , _lowerCamelCase : bool = True , ): A__ = [file for file in os.listdir(SCREAMING_SNAKE_CASE__ ) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )] if identifier is not None: A__ = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for n_ in n_identifier: A__ = [file for file in files if n_ not in file] else: A__ = [file for file in files if n_identifier not in file] A__ = ignore_files or [] ignore_files.append('''__init__.py''' ) A__ = [file for file in files if file not in ignore_files] for file in files: # Open all files print('''Testing''' , SCREAMING_SNAKE_CASE__ ) if only_modules: A__ = file.split('''.''' )[0] try: A__ = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__ ) A__ = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'''{module_identifier} is not a module.''' ) else: A__ = doctest.testfile(str('''..''' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def A__ ( self : List[Any] ): A__ = Path('''src/transformers''' ) A__ = 'modeling' A__ = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ ) def A__ ( self : Dict ): A__ = Path('''src/transformers''' ) A__ = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def A__ ( self : Tuple ): A__ = Path('''src/transformers''' ) A__ = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def A__ ( self : int ): A__ = Path('''src/transformers''' ) A__ = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , n_identifier=SCREAMING_SNAKE_CASE__ ) def A__ ( self : int ): A__ = Path('''docs/source''' ) A__ = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ , only_modules=SCREAMING_SNAKE_CASE__ )
571
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
652
0
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple ): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A__ = flax_key_tuple[:-1] + ('weight',) A__ = torch.permute(lowerCamelCase__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowerCamelCase__ ): # linear layer A__ = flax_key_tuple[:-1] + ('weight',) A__ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ = flax_key_tuple[:-1] + ('weight',) return flax_key_tuple, flax_tensor def UpperCamelCase ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : Any ): if "metadata" in layer: A__ = layer.split("metadata" ) A__ = ''.join(split_layer[0] )[:-1] A__ = [tuple(("metadata" + split_layer[1]).split("/" ) )] elif "kvstore" in layer: A__ = layer.split("kvstore" ) A__ = ''.join(split_layer[0] )[:-1] A__ = [tuple(("kvstore" + split_layer[1]).split("/" ) )] else: A__ = layer.split("/" ) A__ = '/'.join(split_layer[:-1] ) A__ = (split_layer[-1],) if "kvstore/path" in layer: A__ = F"{switch_checkpoint_path}/{checkpoint_info[layer]}" elif "kvstore/driver" in layer: A__ = 'file' else: A__ = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase ( _lowerCamelCase : Dict , _lowerCamelCase : int ): A__ = rename_keys(lowerCamelCase__ ) A__ = {} for k, v in current_block.items(): A__ = v A__ = new_current_block torch.save(lowerCamelCase__ , lowerCamelCase__ ) def UpperCamelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] = WEIGHTS_NAME ): A__ = convert_file_size_to_int(lowerCamelCase__ ) A__ = [] A__ = {} A__ = 0 A__ = 0 os.makedirs(lowerCamelCase__ , exist_ok=lowerCamelCase__ ) with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp: A__ = serialization.msgpack_restore(fp.read() )['optimizer']['target'] A__ = flatten_dict(lowerCamelCase__ , sep="/" ) A__ = {} for layer in checkpoint_info.keys(): A__ = get_key_and_tensorstore_dict( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if curr_real_layer_name in all_layers: A__ = content else: A__ = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A__ = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A__ = torch.tensor(lowerCamelCase__ ) A__ = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A__ = rename_base_flax_keys(tuple(key.split("/" ) ) , lowerCamelCase__ ) A__ = '/'.join(lowerCamelCase__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A__ = os.path.join( lowerCamelCase__ , weights_name.replace(".bin" , F"-{len(lowerCamelCase__ )+1:05d}-of-???.bin" ) ) rename_and_save_block(lowerCamelCase__ , lowerCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) del current_block A__ = {} A__ = 0 A__ = raw_weights.to(getattr(lowerCamelCase__ , lowerCamelCase__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A__ = os.path.join(lowerCamelCase__ , weights_name.replace(".bin" , F"-{len(lowerCamelCase__ )+1:05d}-of-???.bin" ) ) rename_and_save_block(lowerCamelCase__ , lowerCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowerCamelCase__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A__ = {} A__ = {} for idx, shard in enumerate(lowerCamelCase__ ): A__ = weights_name.replace( ".bin" , F"-{idx+1:05d}-of-{len(lowerCamelCase__ ):05d}.bin" ) # len(sharded_state_dicts):05d} A__ = os.path.join(lowerCamelCase__ , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) ) os.rename(lowerCamelCase__ , os.path.join(lowerCamelCase__ , lowerCamelCase__ ) ) A__ = shard for key in shard: A__ = shard_file # Add the metadata A__ = {'total_size': total_size} A__ = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(lowerCamelCase__ , lowerCamelCase__ ) , "w" , encoding="utf-8" ) as f: A__ = json.dumps(lowerCamelCase__ , indent=2 , sort_keys=lowerCamelCase__ ) + '\n' f.write(lowerCamelCase__ ) return metadata, index if __name__ == "__main__": __lowerCAmelCase : int =argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) __lowerCAmelCase : List[Any] =parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase ( ): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A__ = SwitchTransformersConfig.from_pretrained("google/switch-base-8" ) config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" ) A__ = SwitchTransformersForConditionalGeneration.from_pretrained( "/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" ) A__ = TaTokenizer.from_pretrained("t5-small" ) A__ = 'A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.' A__ = tokenizer(lowerCamelCase__ , return_tensors="pt" ).input_ids A__ = model.generate(lowerCamelCase__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
440
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a =logging.get_logger(__name__) # General docstring a ="""RegNetConfig""" # Base docstring a ="""facebook/regnet-y-040""" a =[1, 1088, 7, 7] # Image classification docstring a ="""facebook/regnet-y-040""" a ="""tabby, tabby cat""" a =[ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : Optional[str] = "relu" ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): super().__init__(**SCREAMING_SNAKE_CASE__) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2) __lowerCamelCase : Union[str, Any] = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,strides=SCREAMING_SNAKE_CASE__ ,padding='VALID' ,groups=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution' ,) __lowerCamelCase : int = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') __lowerCamelCase : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : List[Any] = self.convolution(self.padding(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Union[str, Any] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Dict): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = config.num_channels __lowerCamelCase : Dict = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='embedder' ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[int] = shape_list(SCREAMING_SNAKE_CASE__)[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 2, 3, 1)) __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = tf.keras.layers.ConvaD( filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,strides=SCREAMING_SNAKE_CASE__ ,use_bias=SCREAMING_SNAKE_CASE__ ,name='convolution') __lowerCamelCase : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name='normalization') def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False): return self.normalization(self.convolution(SCREAMING_SNAKE_CASE__) ,training=SCREAMING_SNAKE_CASE__) class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') __lowerCamelCase : Dict = [ tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='relu' ,name='attention.0'), tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation='sigmoid' ,name='attention.2'), ] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE__) for layer_module in self.attention: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = hidden_state * pooled return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[Any]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = max(1 ,out_channels // config.groups_width) __lowerCamelCase : Dict = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.2'), ] __lowerCamelCase : Dict = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : int = hidden_state for layer_module in self.layers: __lowerCamelCase : List[str] = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : int = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1 __lowerCamelCase : Tuple = max(1 ,out_channels // config.groups_width) __lowerCamelCase : int = ( TFRegNetShortCut(SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='shortcut') if should_apply_shortcut else tf.keras.layers.Activation('linear' ,name='shortcut') ) __lowerCamelCase : Optional[int] = [ TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=config.hidden_act ,name='layer.0'), TFRegNetConvLayer( SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act ,name='layer.1'), TFRegNetSELayer(SCREAMING_SNAKE_CASE__ ,reduced_channels=int(round(in_channels / 4)) ,name='layer.2'), TFRegNetConvLayer(SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__ ,name='layer.3'), ] __lowerCamelCase : List[Any] = ACTaFN[config.hidden_act] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[int] = hidden_state for layer_module in self.layers: __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : Any = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer __lowerCamelCase : Tuple = [ # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,name='layers.0'), *[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,name=F"layers.{i+1}") for i in range(depth - 1)], ] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any]): for layer_module in self.layers: __lowerCamelCase : Any = layer_module(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,**SCREAMING_SNAKE_CASE__ : Any): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='stages.0' ,)) __lowerCamelCase : Optional[int] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:])): self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__ ,name=F"stages.{i+1}")) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Optional[Any] = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__) @keras_serializable class A_ ( tf.keras.layers.Layer ): _UpperCAmelCase : List[Any] = RegNetConfig def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = config __lowerCamelCase : Optional[int] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE__ ,name='embedder') __lowerCamelCase : Union[str, Any] = TFRegNetEncoder(SCREAMING_SNAKE_CASE__ ,name='encoder') __lowerCamelCase : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE__ ,name='pooler') @unpack_inputs def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,): __lowerCamelCase : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = self.embedder(SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = encoder_outputs[0] __lowerCamelCase : int = self.pooler(SCREAMING_SNAKE_CASE__) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : Union[str, Any] = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) __lowerCamelCase : str = tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : Union[str, Any] = tuple([tf.transpose(SCREAMING_SNAKE_CASE__ ,perm=(0, 3, 1, 2)) for h in encoder_outputs[1]]) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : Optional[int] = '''regnet''' _UpperCAmelCase : List[Any] = '''pixel_values''' @property def lowerCAmelCase ( self : int): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) ,dtype=tf.floataa)} a =r""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : Tuple ,**SCREAMING_SNAKE_CASE__ : Tuple): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : tf.Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : int=False ,): __lowerCamelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple = self.regnet( pixel_values=SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__ ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : RegNetConfig ,*SCREAMING_SNAKE_CASE__ : List[str] ,**SCREAMING_SNAKE_CASE__ : str): super().__init__(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = config.num_labels __lowerCamelCase : Union[str, Any] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE__ ,name='regnet') # classification head __lowerCamelCase : Optional[Any] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='classifier.1') if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : tf.Tensor = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Any=False ,): __lowerCamelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str = self.regnet( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__ ,training=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : Optional[Any] = self.classifier[0](SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.classifier[1](SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states)
652
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" def __init__( self : Dict , *lowerCAmelCase : int , **lowerCAmelCase : List[str] ) -> str: """simple docstring""" warnings.warn( """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use CLIPImageProcessor instead.""" , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
651
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels a =object() # For specifying empty leaf dict `{}` a =object() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCamelCase__ ) - len(lowerCamelCase__ ) + 1 ): __lowerCamelCase : str = [x.match(lowerCamelCase__ ) for x, y in zip(lowerCamelCase__ , ks[i:] )] if matches and all(lowerCamelCase__ ): return True return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: def replace(lowerCamelCase__ , lowerCamelCase__ ): for rule, replacement in rules: if _match(lowerCamelCase__ , lowerCamelCase__ ): return replacement return val return replace def SCREAMING_SNAKE_CASE__ ( ) -> str: return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , lowerCamelCase__ )), (("transformer", "wte", "embedding"), P('mp' , lowerCamelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase__ , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCamelCase__ , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , lowerCamelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = _get_partition_rules() __lowerCamelCase : Optional[Any] = _replacement_rules(lowerCamelCase__ ) __lowerCamelCase : Tuple = {k: _unmatched for k in flatten_dict(lowerCamelCase__ )} __lowerCamelCase : List[Any] = {k: replace(lowerCamelCase__ , lowerCamelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCamelCase__ ) )
652
0
'''simple docstring''' import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def SCREAMING_SNAKE_CASE ( ) -> Tuple: '''simple docstring''' _lowercase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '-m' , '--pretrained_model_name_or_path' , type=lowerCamelCase__ , default=lowerCamelCase__ , required=lowerCamelCase__ , help='Path to pretrained model or model identifier from huggingface.co/models.' , ) parser.add_argument( '-c' , '--caption' , type=lowerCamelCase__ , default='robotic cat with wings' , help='Text used to generate images.' , ) parser.add_argument( '-n' , '--images_num' , type=lowerCamelCase__ , default=4 , help='How much images to generate.' , ) parser.add_argument( '-s' , '--seed' , type=lowerCamelCase__ , default=42 , help='Seed for random process.' , ) parser.add_argument( '-ci' , '--cuda_id' , type=lowerCamelCase__ , default=0 , help='cuda_id.' , ) _lowercase : Dict = parser.parse_args() return args def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Tuple) -> str: '''simple docstring''' if not len(lowerCamelCase__) == rows * cols: raise ValueError('The specified number of rows and columns are not correct.') _lowercase : Dict = imgs[0].size _lowercase : Dict = Image.new('RGB' , size=(cols * w, rows * h)) _lowercase : Any = grid.size for i, img in enumerate(lowerCamelCase__): grid.paste(lowerCamelCase__ , box=(i % cols * w, i // cols * h)) return grid def SCREAMING_SNAKE_CASE ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any="robotic cat with wings" , lowerCAmelCase__ : str=7.5 , lowerCAmelCase__ : Dict=50 , lowerCAmelCase__ : str=1 , lowerCAmelCase__ : Optional[Any]=42 , ) -> List[Any]: '''simple docstring''' _lowercase : Dict = torch.Generator(pipeline.device).manual_seed(lowerCamelCase__) _lowercase : List[str] = pipeline( lowerCamelCase__ , guidance_scale=lowerCamelCase__ , num_inference_steps=lowerCamelCase__ , generator=lowerCamelCase__ , num_images_per_prompt=lowerCamelCase__ , ).images _lowercase : Any = int(math.sqrt(lowerCamelCase__)) _lowercase : Optional[int] = image_grid(lowerCamelCase__ , rows=_rows , cols=num_images_per_prompt // _rows) return grid, images A = parse_args() # Load models and create wrapper for stable diffusion A = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='''tokenizer''') A = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''text_encoder''') A = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='''vae''') A = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''unet''') A = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) A = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, '''best_model.pt''')): A = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, '''unet''', unet) else: A = unet.to(torch.device('''cuda''', args.cuda_id)) A = pipeline.to(unet.device) A , A = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, '''{}.png'''.format('''_'''.join(args.caption.split())))) A = os.path.join(args.pretrained_model_name_or_path, '''_'''.join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, '''{}.png'''.format(idx + 1)))
125
import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list: __lowerCamelCase : Union[str, Any] = [True] * n __lowerCamelCase : List[Any] = False __lowerCamelCase : int = False __lowerCamelCase : Any = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __lowerCamelCase : List[str] = i * 2 while index < n: __lowerCamelCase : Optional[int] = False __lowerCamelCase : List[Any] = index + i __lowerCamelCase : Optional[Any] = [2] for i in range(3 , lowerCamelCase__ , 2 ): if is_prime[i]: primes.append(lowerCamelCase__ ) return primes def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 9_9_9_9_6_6_6_6_3_3_3_3 ) -> int: __lowerCamelCase : Optional[Any] = math.floor(math.sqrt(lowerCamelCase__ ) ) + 1_0_0 __lowerCamelCase : Dict = prime_sieve(lowerCamelCase__ ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Any = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase : Any = primes[prime_index + 1] __lowerCamelCase : Optional[Any] = last_prime**2 __lowerCamelCase : Dict = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase : Tuple = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase : List[Any] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
652
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 SCREAMING_SNAKE_CASE_ ( _a ): """simple docstring""" __lowerCAmelCase : str ='''dandelin/vilt-b32-finetuned-vqa''' __lowerCAmelCase : 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.''' ) __lowerCAmelCase : Dict ='''image_qa''' __lowerCAmelCase : Dict =AutoProcessor __lowerCAmelCase : Tuple =AutoModelForVisualQuestionAnswering __lowerCAmelCase : List[str] =['''image''', '''text'''] __lowerCAmelCase : List[str] =['''text'''] def __init__( self :Any, *snake_case :str, **snake_case :str): """simple docstring""" requires_backends(self, ['vision']) super().__init__(*SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__) def UpperCamelCase__ ( self :List[str], snake_case :"Image", snake_case :str): """simple docstring""" return self.pre_processor(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, return_tensors='pt') def UpperCamelCase__ ( self :Tuple, snake_case :List[str]): """simple docstring""" with torch.no_grad(): return self.model(**SCREAMING_SNAKE_CASE__).logits def UpperCamelCase__ ( self :Optional[int], snake_case :str): """simple docstring""" _lowercase =outputs.argmax(-1).item() return self.model.config.idalabel[idx]
181
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = 1 @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.15 ,SCREAMING_SNAKE_CASE__ : float = 0.01 ,SCREAMING_SNAKE_CASE__ : float = 1348.0 ,SCREAMING_SNAKE_CASE__ : float = 1E-5 ,SCREAMING_SNAKE_CASE__ : int = 1 ,): # standard deviation of the initial noise distribution __lowerCamelCase : int = sigma_max # setable values __lowerCamelCase : List[str] = None self.set_sigmas(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps __lowerCamelCase : Optional[int] = torch.linspace(1 ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,device=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : float = None): __lowerCamelCase : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __lowerCamelCase : Optional[int] = sigma_max if sigma_max is not None else self.config.sigma_max __lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __lowerCamelCase : Optional[Any] = torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE__) ,math.log(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[str]): return torch.where( timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') __lowerCamelCase : List[str] = timestep * torch.ones( sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0]) __lowerCamelCase : str = (timestep * (len(self.timesteps) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __lowerCamelCase : Dict = timesteps.to(self.discrete_sigmas.device) __lowerCamelCase : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device) __lowerCamelCase : Optional[Any] = self.get_adjacent_sigma(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__).to(sample.device) __lowerCamelCase : int = torch.zeros_like(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __lowerCamelCase : int = diffusion.flatten() while len(diffusion.shape) < len(sample.shape): __lowerCamelCase : List[Any] = diffusion.unsqueeze(-1) __lowerCamelCase : Any = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __lowerCamelCase : int = randn_tensor( sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__ ,device=sample.device ,dtype=sample.dtype) __lowerCamelCase : Optional[int] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __lowerCamelCase : Union[str, Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,prev_sample_mean=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler') # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __lowerCamelCase : Optional[int] = randn_tensor(sample.shape ,layout=sample.layout ,generator=SCREAMING_SNAKE_CASE__).to(sample.device) # compute step size from the model_output, the noise, and the snr __lowerCamelCase : str = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean() __lowerCamelCase : Tuple = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __lowerCamelCase : Optional[int] = step_size * torch.ones(sample.shape[0]).to(sample.device) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape) < len(sample.shape): __lowerCamelCase : List[str] = step_size.unsqueeze(-1) __lowerCamelCase : str = sample + step_size * model_output __lowerCamelCase : Any = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,): # Make sure sigmas and timesteps have the same device and dtype as original_samples __lowerCamelCase : int = timesteps.to(original_samples.device) __lowerCamelCase : Any = self.discrete_sigmas.to(original_samples.device)[timesteps] __lowerCamelCase : Optional[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(SCREAMING_SNAKE_CASE__) * sigmas[:, None, None, None] ) __lowerCamelCase : str = noise + original_samples return noisy_samples def __len__( self : Optional[int]): return self.config.num_train_timesteps
652
0
"""simple docstring""" from math import factorial def _a ( _snake_case = 100 ): """simple docstring""" return sum(map(lowerCamelCase__ , str(factorial(lowerCamelCase__ ) ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
341
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' from string import ascii_uppercase lowercase__ = {str(ord(c) - 5_5): c for c in ascii_uppercase} def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: '''simple docstring''' if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''int() can\'t convert non-string with explicit base''' ) if num < 0: raise ValueError('''parameter must be positive int''' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''\'str\' object cannot be interpreted as an integer''' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('''\'float\' object cannot be interpreted as an integer''' ) if base in (0, 1): raise ValueError('''base must be >= 2''' ) if base > 36: raise ValueError('''base must be <= 36''' ) snake_case : Optional[Any] = '' snake_case : Tuple = 0 snake_case : Dict = 0 while div != 1: snake_case : Optional[int] = divmod(lowerCamelCase__ , lowerCamelCase__ ) if base >= 11 and 9 < mod < 36: snake_case : Any = ALPHABET_VALUES[str(lowerCamelCase__ )] else: snake_case : List[str] = str(lowerCamelCase__ ) new_value += actual_value snake_case : Any = num // base snake_case : Any = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(lowerCamelCase__ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 3_7): for num in range(1_0_0_0): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
638
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : Optional[int] = [file for file in files if n_ not in file] else: __lowerCamelCase : Dict = [file for file in files if n_identifier not in file] __lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : Optional[int] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : int = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = 'modeling' __lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = Path('src/transformers') __lowerCamelCase : Optional[int] = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : str = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = Path('src/transformers') __lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = Path('docs/source') __lowerCamelCase : str = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
652
0
class __lowercase : # Public class to implement a graph """simple docstring""" def __init__( self , A , A , A ) -> Tuple: '''simple docstring''' lowerCamelCase = row lowerCamelCase = col lowerCamelCase = graph def __A ( self , A , A , A ) -> List[str]: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def __A ( self , A , A , A ) -> Tuple: '''simple docstring''' lowerCamelCase = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowerCamelCase = [-1, 0, 1, -1, 1, -1, 0, 1] lowerCamelCase = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE__ ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE__ ) def __A ( self ) -> Optional[Any]: # And finally, count all islands. '''simple docstring''' lowerCamelCase = [[False for j in range(self.COL )] for i in range(self.ROW )] lowerCamelCase = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += 1 return count
457
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ="""▁""" a ={"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} a ={ """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } a ={"""vinai/bartpho-syllable""": 1024} class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]="<s>" ,SCREAMING_SNAKE_CASE__ : Any="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="</s>" ,SCREAMING_SNAKE_CASE__ : List[str]="<s>" ,SCREAMING_SNAKE_CASE__ : int="<unk>" ,SCREAMING_SNAKE_CASE__ : Dict="<pad>" ,SCREAMING_SNAKE_CASE__ : List[str]="<mask>" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = vocab_file __lowerCamelCase : Tuple = monolingual_vocab_file __lowerCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__)) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Any = cnt cnt += 1 with open(SCREAMING_SNAKE_CASE__ ,'r' ,encoding='utf-8') as f: for line in f.readlines(): __lowerCamelCase : Any = line.strip().split()[0] __lowerCamelCase : List[str] = len(self.fairseq_tokens_to_ids) if str(SCREAMING_SNAKE_CASE__) not in self.fairseq_tokens_to_ids: __lowerCamelCase : Dict = len(self.fairseq_tokens_to_ids) __lowerCamelCase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): __lowerCamelCase : Tuple = self.__dict__.copy() __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : str = {} __lowerCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : Tuple = [self.cls_token_id] __lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Dict = [self.sep_token_id] __lowerCamelCase : 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 lowerCAmelCase ( self : List[str]): return len(self.fairseq_ids_to_tokens) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): return self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Any = ''.join(SCREAMING_SNAKE_CASE__).replace(SCREAMING_SNAKE_CASE__ ,' ').strip() return out_string def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) __lowerCamelCase : Union[str, Any] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) if os.path.abspath(self.monolingual_vocab_file) != os.path.abspath( SCREAMING_SNAKE_CASE__) and os.path.isfile(self.monolingual_vocab_file): copyfile(self.monolingual_vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.monolingual_vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'w' ,encoding='utf-8') as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(SCREAMING_SNAKE_CASE__)} \n") return out_vocab_file, out_monolingual_vocab_file
652
0
'''simple docstring''' import torch from transformers import AutoModel class _UpperCAmelCase ( torch.nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): '''simple docstring''' super(SCREAMING_SNAKE_CASE__,self ).__init__() __lowerCAmelCase = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE__,return_dict=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = torch.nn.CosineSimilarity(3,1e-08 ) __lowerCAmelCase = torch.nn.Softmax(dim=1 ) def lowerCamelCase__ ( self,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' return self.bert(**SCREAMING_SNAKE_CASE__ ).last_hidden_state def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' return token_embeddings.sum(2,keepdim=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=1 ): '''simple docstring''' return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = W_supports['sizes'].tolist() __lowerCAmelCase = W_supports['start_token_id'].item() __lowerCAmelCase = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __lowerCAmelCase = self.BERT(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.BERT(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = W_supports['input_ids'] == start_token_id __lowerCAmelCase = W_supports['input_ids'] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE__ ): if i == 0: __lowerCAmelCase = 0 else: __lowerCAmelCase = support_sizes[i - 1] __lowerCAmelCase = S[s : s + size][start_token_masks[s : s + size]] __lowerCAmelCase = S[s : s + size][end_token_masks[s : s + size]] __lowerCAmelCase = torch.matmul(q[i],s_start.T ).sum(1 ).softmax(0 ) __lowerCAmelCase = torch.matmul(q[i],s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __lowerCAmelCase = torch.vstack((p_starts, p_start) ) __lowerCAmelCase = torch.vstack((p_ends, p_end) ) else: __lowerCAmelCase = p_start __lowerCAmelCase = p_end return p_starts, p_ends
689
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_3 ,SCREAMING_SNAKE_CASE__ : int=3_0 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=3_2 ,SCREAMING_SNAKE_CASE__ : Any=2 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : str=3 ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : Optional[Any]=2 ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Dict = image_size __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = is_training __lowerCamelCase : List[Any] = use_labels __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : List[str] = scope __lowerCamelCase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCamelCase : str = (image_size // patch_size) ** 2 __lowerCamelCase : str = num_patches + 2 def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : List[Any] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any]): return DeiTConfig( 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=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Optional[Any] = TFDeiTModel(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = TFDeiTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images __lowerCamelCase : int = 1 __lowerCamelCase : Tuple = TFDeiTForMaskedImageModeling(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.type_sequence_label_size __lowerCamelCase : List[Any] = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = TFDeiTForImageClassification(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size)) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = config_and_inputs __lowerCamelCase : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) _UpperCAmelCase : List[Any] = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = TFDeiTModelTester(self) __lowerCamelCase : Optional[int] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : str): self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def lowerCAmelCase ( self : List[Any]): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,tf.keras.layers.Dense)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Any = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=False): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters: del inputs_dict["labels"] return inputs_dict @slow def lowerCAmelCase ( self : Optional[int]): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Union[str, Any] = TFDeiTModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: __lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224') __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : Tuple = prepare_img() __lowerCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='tf') # forward pass __lowerCamelCase : int = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Optional[int] = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = tf.constant([-1.0266, 0.1912, -1.2861]) self.assertTrue(np.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
652
0
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: UpperCamelCase__ : List[str] = k_size // 2 UpperCamelCase__ : Tuple = mgrid[0 - center : k_size - center, 0 - center : k_size - center] UpperCamelCase__ : int = 1 / (2 * pi * sigma) * exp(-(square(lowerCamelCase__ ) + square(lowerCamelCase__ )) / (2 * square(lowerCamelCase__ )) ) return g def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: UpperCamelCase__ : str = image.shape[0], image.shape[1] # dst image height and width UpperCamelCase__ : int = height - k_size + 1 UpperCamelCase__ : List[str] = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows UpperCamelCase__ : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) UpperCamelCase__ : Any = 0 for i, j in product(range(lowerCamelCase__ ) , range(lowerCamelCase__ ) ): UpperCamelCase__ : str = ravel(image[i : i + k_size, j : j + k_size] ) UpperCamelCase__ : int = window row += 1 # turn the kernel into shape(k*k, 1) UpperCamelCase__ : Tuple = gen_gaussian_kernel(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : str = ravel(lowerCamelCase__ ) # reshape and get the dst image UpperCamelCase__ : int = dot(lowerCamelCase__ , lowerCamelCase__ ).reshape(lowerCamelCase__ , lowerCamelCase__ ).astype(lowerCamelCase__ ) return dst if __name__ == "__main__": # read original image UpperCAmelCase__ : Tuple = imread(r'''../image_data/lena.jpg''') # turn image in gray scale value UpperCAmelCase__ : List[str] = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size UpperCAmelCase__ : int = gaussian_filter(gray, 3, sigma=1) UpperCAmelCase__ : Dict = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('''gaussian filter with 3x3 mask''', gaussianaxa) imshow('''gaussian filter with 5x5 mask''', gaussianaxa) waitKey()
410
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] _UpperCAmelCase : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
652
0
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCamelCase ( a_ ): """simple docstring""" a = ['''image_processor''', '''tokenizer'''] a = '''Pix2StructImageProcessor''' a = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : str): _A : List[str] = False super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def __call__( self : int , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[int] = 2048 , SCREAMING_SNAKE_CASE : int = 0 , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[bool] = None , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE : Union[str, Any] , ): 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: _A : List[str] = self.tokenizer _A : Any = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values _A : int = self.image_processor( SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_patches=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox _A : Optional[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: _A : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if "attention_mask" in text_encoding: _A : str = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: _A : Optional[int] = text_encoding.pop('input_ids') else: _A : List[str] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def A ( self : List[str] , *SCREAMING_SNAKE_CASE : Optional[int] , **SCREAMING_SNAKE_CASE : Union[str, Any]): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) def A ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE : str , **SCREAMING_SNAKE_CASE : Optional[int]): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) @property def A ( self : List[str]): _A : Optional[Any] = self.tokenizer.model_input_names _A : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
128
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
652
0